views:

87

answers:

4

This question is more of a "what is the best/easiest way to do this 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.

Any help would be great, even if you point me to a similar problem I tried Google and such.

A: 

Regex:

.*id[=]([0-9]*).*$
Priyank Bolia
+1  A: 

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];
kemp
+2  A: 

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
RMcLeod
kemp
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.
kemp
A: 

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

Digital Craft Studios