user3388884
user3388884

Reputation: 5068

Using preg_match in php to find substring given string?

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";

Upvotes: 1

Views: 998

Answers (1)

Sam
Sam

Reputation: 20486

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

Upvotes: 3

Related Questions