搜索另一个字符串中是否存在字符串

时间:2011-04-25 10:47:02

标签: php

为了我的目的,我这样做了:

<?php
$mystring = 'Gazole,';
$findme   = 'Sans Plomb 95';
$pos = strpos($mystring, $findme);

if ($pos >= 0) {
    echo "The string '$findme' was found in the string '$mystring'";
    echo " and exists at position $pos";
} else {
    echo "The string '$findme' was not found in the string '$mystring'";
}
?>

但是,它始终执行此分支:

echo "The string '$findme' was found in the string '$mystring'";
echo " and exists at position $pos";

虽然我正在搜索的字符串不存在。

请提前帮助:))

7 个答案:

答案 0 :(得分:14)

正确的做法是:

if ($pos !== false) {
    echo "The string '$findme' was found in the string '$mystring'";
    echo " and exists at position $pos";
} else {
    echo "The string '$findme' was not found in the string '$mystring'";
}

请参阅文档中的giant red warning

答案 1 :(得分:3)

如果找不到字符串,

strpos将返回布尔值false。您的测试应该是$pos !== false而不是$pos >= 0

请注意,标准比较运算符不考虑操作数的类型,因此false被强制转换为0。仅当操作数的类型和值匹配时,===!==运算符才会生成true

答案 2 :(得分:1)

请参阅manual page

上的警告

您还需要检查是否$pos !== false

答案 3 :(得分:1)

如果找不到字符串,

strpos()将返回FALSE。 当您检查$ pos&gt; = 0时,您正在接受FALSE值。

试试这个:

<?php
$mystring = 'Gazole,';
$findme   = 'Sans Plomb 95';
$pos = strpos($mystring, $findme);


if ($pos !== false) {
    echo "The string '$findme' was found in the string '$mystring'";
    echo " and exists at position $pos";
} else {
       echo "The string '$findme' was not found in the string '$mystring'";

}
?>

答案 4 :(得分:1)

你好php中的malek strpos方法会在找不到字符串时返回值为false的布尔值,如果找到它将返回int中的位置。

参考此Link to study about strpos

答案 5 :(得分:0)

if (strpos($mystring, $findme) !== false) {
    echo 'true';
}

答案 6 :(得分:0)

完全不同的方法而无需担心索引:

if (str_replace($strToSearchFor, '', $strToSearchIn) <> $strToSearchIn) {
    //strToSearchFor is found inside strToSearchIn

您正在做的是替换子字符串的所有出现,并检查结果是否与原始字符串相同。

相关问题