开发者

PHP Regex help, getting part of a link

开发者 https://www.devze.com 2023-01-21 07:26 出处:网络
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>

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, wh开发者_运维知识库ich 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


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消