hi all. need some quick help for a php newb.
<a href="/test/pagename/">
i need php to get "pagename" from that href attribute and set it as a variable. i need to compare it with another variable i'm using.
thanks so much!
| SitePoint Sponsor |
hi all. need some quick help for a php newb.
<a href="/test/pagename/">
i need php to get "pagename" from that href attribute and set it as a variable. i need to compare it with another variable i'm using.
thanks so much!


If you already have a string with just the complete anchor tag, this code will work.
PHP Code:$string = "<a href=\"/test/pagename/\">";
$pattern = "<a.+href=\"(.+)\".+>";
preg_match($pattern, $string, $matches);
$matches = array_values(array_filter(explode('/', $matches[1])));
$pagename = $matches[count($matches)-1];
Please remember to use the non-greedy modifier (which i believe is ?) on your patterns...


Star, would you be so kind as to show a pattern for this that does so?
Basically, anywhere you go for .+ (or .*), make it .+? ...
<a href="quack"></a><a href="moo"></a>
Your pattern, greedily, could potentially return a single value containing { quack"></a><a href="moo }, rather than the 2 values expected.


Thanks for pointing that out, StarLion. That's been a thorn in m side I've always had some trouble with. The new pattern looks like this:
PHP Code:$pattern = "<a.+?href=\"(.+?)\".*?>";
PHP Code:$string = '<a href="/test/pagename/">';
preg_match_all('/href="(.*?)"/', $string, $matches);
$array = explode("/", trim($matches[1][0], '/'));
echo $array[count($array) - 1];
Bookmarks