1

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 &

3
  • Will it always be this length and this format? So 6 letters or numbers hyphen 3 letters? Commented Sep 20, 2012 at 21:46
  • hey Daedalus i tried preg_match("/id=*&", $string); , sorry am noob Commented Sep 20, 2012 at 21:48
  • 3
    why insist on using a regexp when PHP has a parse_str() function to do that job - php.net/manual/en/function.parse-str.php Commented Sep 20, 2012 at 21:49

3 Answers 3

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

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]);

5 Comments

so it is like preg_match("/=([^&]*)&/", $string); huh >
Note: depending on what you are trying to match this could produce false positives in the sense that if you have another place where you have =gibberish& then it will still match that part. I like my regex patterns to match exactly and only what I am looking for.
@ajon - True I added id before the equal sign to make sure you will only get the id value.
Couldn't you also do /id=(.*?)&/?
@RocketHazmat - Yes you could.
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'];

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.