Page 1 of 1
How to extract a string from a URL?
Posted: Mon May 18, 2009 11:35 am
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.
Re: How to extract a string from a URL?
Posted: Mon May 18, 2009 2:05 pm
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

Re: How to extract a string from a URL?
Posted: Mon May 18, 2009 2:16 pm
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)?
Re: How to extract a string from a URL?
Posted: Mon May 18, 2009 3:05 pm
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.
Re: How to extract a string from a URL?
Posted: Mon May 18, 2009 3:58 pm
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;
}