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.
How to extract a string from a URL?
Moderator: General Moderators
- 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?
Use Mod Rewrite.
.htaccess
php.php
It is too easy 
.htaccess
Code: Select all
RewriteEngine On
RewriteRule ^([0-9]+)-([^0-9]*[a-zA-Z0-9]+)$ index.php?var=$1&var2=$2Code: Select all
<?php
if(isset($_GET['var'])) {
echo '<pre>';
print_r($_GET);
}
?>- 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?
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)?
- 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?
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.
Re: How to extract a string from a URL?
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;
}