Reputation: 5068
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
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)
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)
Upvotes: 3