在php中使用preg_match查找给定字符串的子字符串?

在php中使用preg_match查找给定字符串的子字符串?,php,preg-match,Php,Preg Match,如何在PHP中使用preg_match来获取以下字符串中的子字符串D30 $string = "random text sample=D30 more random text"; 将匹配组分配给第三个参数,并在匹配时返回1,在不匹配时返回0。因此,检查preg_match()==true,如果是,您的值将在$matches[0]中 $string = "random text sample=D30 more random text"; if(preg_match('/(?<=sample

如何在PHP中使用
preg_match
来获取以下字符串中的子字符串
D30

$string = "random text sample=D30 more random text";
将匹配组分配给第三个参数,并在匹配时返回1,在不匹配时返回0。因此,检查
preg_match()==true
,如果是,您的值将在
$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)
$string = "random text sample=D30 more random text";
if(preg_match('/sample=(\S+)/', $string, $matches)) {
    $value = $matches[1];
    echo $value; // D30
}
sample= (?# match sample= literally)
(       (?# start capture group)
 \S+    (?# match 1+ characters of non-whitespace)
)       (?# end capture group)

您不需要使用
preg\u match()
进行此操作。只需使用
explode()
$result=explode('=',$str)[1]。完全可以使用explode()完成。感谢您的及时回复。请参阅上面的更改。谢谢此演示返回“未提取匹配组”。。。我没有使用任何匹配组,而是只匹配了您想要的部分。这意味着您的值在
$matches[0]
中,而不是
$matches[1]
中。我将使用另一种方法进行更新。如果有帮助,请接受,我还提供了一个使用捕获组而不是查找组的示例。如果可能的话,我更喜欢lookaround方法,但是熟悉这两种方法很好。