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

时间:2021-03-16 19:22:21

I am trying to check whether a phrase of the form $str."s[num]", for example hello3his12, where in this case $str="hello3hi", exists in a string $string, and if it does return the value of [num] as $num, where in this case $num=12.

我试图检查$ str。“s [num]”形式的短语,例如hello3his12,在这种情况下$ str =“hello3hi”,是否存在于字符串$ string中,如果它确实返回值[num]的数字为$ num,在这种情况下$ num = 12。

This is what I tried to to check where a phrase exists in $string

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

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

problem is this always returns false, does anyone know why?

问题是这总是返回假,有谁知道为什么?

1 个解决方案

#1


1  

As mario says in his comment, ^ matches the start of the string, $ the end of the string. So in your example code, preg_match returns false because there are additional characters in your string on both sides of the string you want to match:

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

(dont:jake3rs120 [mik])

Your code would work if the value of $string was jake3rs120.

如果$ string的值为jake3rs120,则代码将起作用。

So to make it match your example string, just remove the ^ and $:

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

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

To get the number after s, use the third parameter of preg_match:

要获得s之后的数字,请使用preg_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';
}

#1


1  

As mario says in his comment, ^ matches the start of the string, $ the end of the string. So in your example code, preg_match returns false because there are additional characters in your string on both sides of the string you want to match:

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

(dont:jake3rs120 [mik])

Your code would work if the value of $string was jake3rs120.

如果$ string的值为jake3rs120,则代码将起作用。

So to make it match your example string, just remove the ^ and $:

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

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

To get the number after s, use the third parameter of preg_match:

要获得s之后的数字,请使用preg_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';
}