Samsquanch
Samsquanch

Reputation: 9146

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.

Upvotes: 1

Views: 89

Answers (2)

Jacob Relkin
Jacob Relkin

Reputation: 163308

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'];

Upvotes: 1

t3rse
t3rse

Reputation: 10124

Perhaps a better tactic over using a regular expressoin in this case is to use parse_url.

You can use that to get the query (what comes after the ? in your URL) and split on the '&' character and then the '=' to put things into a nice dictionary.

Upvotes: 2

Related Questions