查找字符串的正则表达式

Can anyone help me with finding regular expression for the below

$string = "id=A12dk9-mds&name=4950";

I need to find regular expression to find a dynamic value (A12dk9-mds in this example).

i.e the dynamic content between = and &

A simple regex can be used for that.

/id=([^&]*)&/

Explanation:

  • id= matches id=
  • ([^&]*) matches anything but the & symbol as much as possible and returns that
  • & matches the &

As long as you know they will always be between a = and a & this will work.

PHP Code:

$string = "id=A12dk9-mds&name=4950";
preg_match('/id=([^&]*)&/',$string, $answer);
print_r($answer[1]);

RegEx is the wrong tool here. This looks like a query string, so let's use PHP's query string parser, parse_str.

$string = "id=A12dk9-mds&name=4950";
parse_str($string, $parsed);
echo $parsed['id'];

As @MarkBaker has stated, the best way to do this is not regex, but parse_str() since you are actually dealing with a query string of a url.

Therefore, the below should work fine:

parse_str($string,$arr);
echo $arr['id']; // A12dk9-mds