How to extract a string from a URL?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
becky-atlanta
Forum Commoner
Posts: 74
Joined: Thu Feb 26, 2009 6:26 pm
Location: Atlanta, GA

How to extract a string from a URL?

Post by becky-atlanta »

I need to extract the object id from an URL. I went through all str functions and could not put it together yet.

Here is the example:
http://odeo.com/episodes/3005473-Arkia- ... 2-missiles

I need to extract "3005473" in this case, but the URL is a variable. The id changes. The string, "http://odeo.com/episodes/", is static.

Please advise.
Defiline
Forum Commoner
Posts: 59
Joined: Tue May 05, 2009 5:34 pm

Re: How to extract a string from a URL?

Post by Defiline »

Use Mod Rewrite.

.htaccess

Code: Select all

RewriteEngine On
 
RewriteRule ^([0-9]+)-([^0-9]*[a-zA-Z0-9]+)$ index.php?var=$1&var2=$2
php.php

Code: Select all

<?php
 
if(isset($_GET['var'])) {
    echo '<pre>';
    print_r($_GET);
}
 
?>
It is too easy :)
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: How to extract a string from a URL?

Post by John Cartwright »

That is the url you that will be requested on your server, and you just want to acheive clean urls? or are you just parsing url string(s)?
User avatar
becky-atlanta
Forum Commoner
Posts: 74
Joined: Thu Feb 26, 2009 6:26 pm
Location: Atlanta, GA

Re: How to extract a string from a URL?

Post by becky-atlanta »

They are dynamic URLs that I am getting from a RSS feed. The I want to extract the object IDs from the URL for another function.
User avatar
Zoxive
Forum Regular
Posts: 974
Joined: Fri Apr 01, 2005 4:37 pm
Location: Bay City, Michigan

Re: How to extract a string from a URL?

Post by Zoxive »

If its from an RSS feed then you can use regex to extract that number, or if thats to complicated since the url is not changing you can use something like explode.

Code: Select all

<?php
$data = array(
  'http://odeo.com/episodes/3005473-Arkia-pilot-dodges-2-missiles',
  'http://odeo.com/episodes/2998353-Sbarro-bombing-Live-Report',
  'http://odeo.com/episodes/24184288-Michael-Steele-Interview-frm-2004',
);
 
function explo($line){
  $exploded = explode('/',$line);
  $last = explode('-',$exploded[4]);
  return $last[0];
}
 
function pregmatch($line){
  preg_match('/\/([0-9]+)-/i', $line, $result);
  return $result[1];
}
 
echo 'explode', PHP_EOL;
foreach($data as $dt){
  echo explo($dt), PHP_EOL;
}
echo 'preg_match', PHP_EOL;
foreach($data as $dt){
  echo pregmatch($dt), PHP_EOL;
}
Post Reply