简体   繁体   中英

Regex, how to match this string?

I have the url http://domain.com/script.php?l=7&p=146#p146 . I want to be able to get the number after p=, without the #. Also, the hash may not always be there, so sometimes it could turn out as script.php?l=7&p=146 . I know it's something to do with the regex character + , but I'm not completely sure on how to use it. Can someone please create the regex and explain how it works?

No need for regular expressions here.

$query = parse_url("http://domain.com/script.php?l=7&p=146#p146", PHP_URL_QUERY);
parse_str($query, $params);
echo $params['p'];

parse_url can get you all the distinct elements of a URL. And parse_str takes a query string (that stuff you find between ? and an optional # in a URL) and figures out the different parameters for you. You could also omit the parameter $params to the function, then parse_str would define some variables for you (afterward you could find the result in $p ). But I personally rather dislike using parse_str with this side effect.

If you want to read up some more: PHP documentation on parse_url and parse_str

Don't reinvent the wheel. Use a built-in function, such as parse_url to parse the URL.

Documentation and examples: http://php.net/manual/en/function.parse-url.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM