php getting part of a URL into a string
This question is more of a "what is the best/easiest way to do"-type-of-question. I would like to grab just the users id from a string such as
<a href="/profile.php?rdc332738&id=123456&refid=22">User name</a>
I would like to parse the string and get just the "123456"
part of it.
I was thinking I could explode the string but then I would get id=123456&blahblahblah
开发者_C百科 and I suppose I would have to somehow dynamically remove the trash from the end. I think this may be possible with regex but I'm fairly new to PHP and so regex is a little above me.
The function parse_str() will help here
$str = "profile.php?rdc332738&id=123456&refid=22";
parse_str($str);
echo $id; //123456
echo $refid; //22
Just grab any character from id=
up to &
or "
(the latter accounts for the case where id
is put last on the query string)
$str = 'a href="/profile.php?rdc332738&id=123456&refid=22">User name</a>';
preg_match('/id=([^&"]+)/', $str, $match);
$id = $match[1];
Regex:
.*id[=]([0-9]*).*$
if you explode the string:
$string="<a href="/profile.php?rdc332738&id=123456&refid=22">User name</a>"
$string_components=explode('&','$string');
The user id part (id=123456) will be:
$user_id_part=$string_components[1];
then you could do a string replace:
$user_id=str_replace('id=','$user_id_part');
And you have the user id
精彩评论