Search code examples
phpregexhrefurl-parameterssanitization

Get value of a particular key in the query string of an <a> tag's href value


I'm trying to write a regex in PHP that in a line like

 <a href="mypage.php?(some junk)&p=12345&(other junk)" other link stuff>Text</a>

and it will only return me "p=12345", or even "12345". Note that the (some junk)& and the &(otherjunk) may or may not be present. Can I do this with one expression, or will I need more than one? I can't seem to work out how to do it in one, which is what I would like if at all possible. I'm also open to other methods of doing this, if you have a suggestion.


Solution

  • Use parse_url and parse_str:

    $url = 'mypage.php?(some junk)&p=12345&(other junk)';
    $parsed_url = parse_url($url);
    parse_str($parsed_url['query'], $parsed_str);
    echo $parsed_str['p'];