tags:

views:

38

answers:

2

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.

Thanks

+2  A: 

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.

David in Dakota
+1  A: 

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'];
Jacob Relkin
@user48518, I updated my answer to use `parse_str`.
Jacob Relkin
I was actually unable to get this to work until I changed $parsed_str = parse_str($parsed_url['query']); to parse_str($parsed_url['query'], $parsed_str);, but thanks for your reply, it was exactly what I was looking for.
@user48518, Sorry for that. Glad I could help!
Jacob Relkin