Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何在字符串中查找特定短语?_Php_Regex_String_Text - Fatal编程技术网

Php 如何在字符串中查找特定短语?

Php 如何在字符串中查找特定短语?,php,regex,string,text,Php,Regex,String,Text,我试图检查$str.“s[num]”形式的短语是否存在,例如hello3his 12,在本例中,$str=“hello3hi”,它是否以$string的形式返回[num]的值,在本例中,$num=12 这就是我试图检查$string中短语的位置 $string ="(dont:jake3rs120 [mik])"; $str = "jake3r"; if(preg_match('~^'.$str.'s([0-9]+)$~', $string)){ echo 'phrase exists'

我试图检查
$str.“s[num]”
形式的短语是否存在,例如
hello3his 12
,在本例中,
$str=“hello3hi”
,它是否以
$string
的形式返回[num]的值,在本例中,
$num=12

这就是我试图检查$string中短语的位置

$string ="(dont:jake3rs120 [mik])";
$str = "jake3r";
if(preg_match('~^'.$str.'s([0-9]+)$~', $string)){
    echo 'phrase exists';
}else{
    echo'phrase does not exist';
}

问题是它总是返回false,有人知道为什么吗?

正如mario在他的评论中所说,
^
匹配字符串的开头,
$
匹配字符串的结尾。因此,在您的示例代码中,
preg_match
返回
false
,因为您希望匹配的字符串两侧都有其他字符:

(dont:jake3rs120 [mik])
如果
$string
的值为
jake3rs120
,则代码可以工作


因此,要使其与示例字符串匹配,只需删除
^
$

if(preg_match('~'.$str.'s([0-9]+)~', $string)) {
    echo 'phrase exists';
} else {
    echo'phrase does not exist';
}
要获取
s
之后的数字,请使用
preg\u match
的第三个参数:

if(preg_match('~'.$str.'s([0-9]+)~', $string, $matches)) {
    echo 'phrase exists';
    echo $matches[1]; // Echoes the number after s.
} else {
    echo'phrase does not exist';
}

^
$
是主题开始和结束标记。它们不是regex装饰。谢谢,我现在明白了。如果短语存在,是否可以获取
s
后面的数字?