0

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&amp;id=123456&amp;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 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.

4 Answers 4

2

The function parse_str() will help here

$str = "profile.php?rdc332738&amp;id=123456&amp;refid=22";
parse_str($str);
echo $id; //123456
echo $refid; //22
Sign up to request clarification or add additional context in comments.

2 Comments

Seems like parse_str() doesn't handle the (correct) form with &amp; but only understands single &, so this code doesn't work.
Also, it just works if the string contains only the query string, if you include profile.php? it gets confused and loses the first argument.
1

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&amp;id=123456&amp;refid=22">User name</a>';

preg_match('/id=([^&"]+)/', $str, $match);
$id = $match[1];

Comments

0

Regex:

.*id[=]([0-9]*).*$

Comments

0

if you explode the string:

$string="<a href="/profile.php?rdc332738&amp;id=123456&amp;refid=22">User name</a>"
$string_components=explode('&amp;','$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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.