1

How do I use preg_match in PHP to get the substring D30 in the following string?

$string = "random text sample=D30 more random text";
3
  • 1
    You don't need preg_match() for this. Just use explode(): $result = explode('=', $str)[1];. Commented May 14, 2014 at 20:26
  • exactly it could be done using explode() Commented May 14, 2014 at 20:28
  • Thank you for your prompt response. Please see changes above. Thanks! Commented May 14, 2014 at 20:29

1 Answer 1

3

preg_match() will assign the match groups to the third parameter and return the 1 on match and 0 on no match. So check if preg_match() == true, and if it is, your value will be in $matches[0].

$string = "random text sample=D30 more random text";
if(preg_match('/(?<=sample=)\S+/', $string, $matches)) {
    $value = reset($matches);
    echo $value; // D30
}

RegEx:

(?<=     (?# start lookbehind)
 sample= (?# match sample= literally)
)        (?# end lookbehind)
\S+      (?# match 1+ characters of non-whitespace)

Demo


Using capture groups instead of lookbehind:

$string = "random text sample=D30 more random text";
if(preg_match('/sample=(\S+)/', $string, $matches)) {
    $value = $matches[1];
    echo $value; // D30
}

RegEx:

sample= (?# match sample= literally)
(       (?# start capture group)
 \S+    (?# match 1+ characters of non-whitespace)
)       (?# end capture group)

Demo

Sign up to request clarification or add additional context in comments.

3 Comments

This demo returned "No match groups were extracted"... wh
I didn't use any match groups, instead I only matched the part you wanted..meaning your value is in $matches[0] not $matches[1]. I'll update with an alternative method.
Accept if it helped, I also included an example using capture groups instead of lookarounds. I prefer the lookaround method when possible, but its good to be familiar with both.

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.