如何在PHP中使用preg_match
来获取以下字符串中的子字符串D30
?
$string = "random text sample=D30 more random text";
答案 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
}
使用捕获组而不是lookbehind:
sample= (?# match sample= literally)
( (?# start capture group)
\S+ (?# match 1+ characters of non-whitespace)
) (?# end capture group)
<强>正则表达式:强>
{{1}}