SitePoint Sponsor

User Tag List

Results 1 to 7 of 7

Thread: grab href attribute?

  1. #1
    SitePoint Enthusiast
    Join Date
    Apr 2005
    Posts
    40
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Question grab href attribute?

    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!

  2. #2
    SitePoint Addict Zarin Denatrose's Avatar
    Join Date
    Jan 2009
    Location
    Surrey BC, Canada
    Posts
    309
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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]; 

  3. #3
    Keeper of the SFL StarLion's Avatar
    Join Date
    Feb 2006
    Location
    Atlanta, GA, USA
    Posts
    3,518
    Mentioned
    31 Post(s)
    Tagged
    0 Thread(s)
    Please remember to use the non-greedy modifier (which i believe is ?) on your patterns...

  4. #4
    SitePoint Addict Zarin Denatrose's Avatar
    Join Date
    Jan 2009
    Location
    Surrey BC, Canada
    Posts
    309
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Star, would you be so kind as to show a pattern for this that does so?

  5. #5
    Keeper of the SFL StarLion's Avatar
    Join Date
    Feb 2006
    Location
    Atlanta, GA, USA
    Posts
    3,518
    Mentioned
    31 Post(s)
    Tagged
    0 Thread(s)
    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.

  6. #6
    SitePoint Addict Zarin Denatrose's Avatar
    Join Date
    Jan 2009
    Location
    Surrey BC, Canada
    Posts
    309
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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=\"(.+?)\".*?>"

  7. #7
    rajug.replace('Raju Gautam'); bronze trophy Raju Gautam's Avatar
    Join Date
    Oct 2006
    Location
    Kathmandu, Nepal
    Posts
    4,004
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •