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

时间:2014-05-14 20:24:48

标签: php preg-match

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

$string = "random text sample=D30 more random text";

1 个答案:

答案 0 :(得分:3)

preg_match()会将匹配组分配给第三个参数,并在匹配时返回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 }

(?<=     (?# 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
}

Demo


使用捕获组而不是lookbehind:

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

<强>正则表达式:

{{1}}

Demo