如何检查字符串是否不包含特定短语?

问题描述 投票:0回答:8

如何反转 PHP 中如何检查字符串是否包含特定单词?

if (strpos($a,'are') !== false) {
    echo 'true';
}

因此,如果

true
not
are 中找到,它就会回显
$a

php
8个回答
74
投票

代码在这里:

if (strpos($a, 'are') !== false) {
    // The word WAS found
}

表示在字符串中找到了该单词。如果删除 NOT (!) 运算符,则条件颠倒了。

if (strpos($a, 'are') === false) {
    // The word was NOT found
}

=== 非常重要,因为如果单词 'are' 位于字符串的最开头,strpos 将返回 0,并且由于 0 松散地等于 FALSE,因此您会在尝试找出问题所在时感到沮丧。 === 运算符可以非常准确地检查结果是否为布尔值 false 而不是 0。

举个例子,

if (!strpos($a, 'are')) {
    // String Not Found
}

如果 $a = "are you come over night?",这段代码会说找不到字符串 'are',因为 'are' 的位置是 0,即字符串的开头。这就是为什么使用 === false 检查如此重要。


7
投票

使用 strstr():

if (!strstr($var, 'something')) {
    // $var does not contain 'something'
}

或 strpos():

if (strpos($var, 'something') === false) {
    // $var does not contain 'something'
} 

或者 stripos() 如果您想要不区分大小写的搜索。

strpos() 有点更快


3
投票

看到它你可能会踢自己......

if (!strpos($a,'are') !== false) {
    echo 'true';
}

0
投票

试试这个

$string = "This is beautiful world.";
$$string = "Beautiful";
    preg_match('/\b(express\w+)\b/', $string, $x); // matches expression

    \b is a word boundary
    \w+ is one or more "word" character
    \w* is zero or more "word" characters
    enter code here

请参阅 PCRE 的转义序列手册。


0
投票
如果搜索字符串位于字符串的开头,则

strpos() !== false 会给出错误的返回值。所以你最好使用 strstr(),它会给你一个准确的结果。

if (!strstr($mystring, 'Hello')) {
    // $mystring does not contain 'Hello' nowhere, 
    // even not at the beginning of the string
}
else{
    // Your code goes here....
}

0
投票
function find_word($text, $word) {
/*yuHp*/
$sizeText = strlen($text);
$sizeWord = strlen($word);
$text = strtolower($text);
$word = strtolower($word);
$contadorText = 0;
$pontuacao = 0;
while ($contadorText < $sizeText) {
    if ($text[$contadorText] == $word[$pontuacao]) {
        $pontuacao++;
        if ($pontuacao == $sizeWord) {
            return true;
        }
    } else {
        $pontuacao = 0;
    }
    $contadorText++;
}

return false;
}

if (!find_word('today', 'odf')){
   //did not find 'odf' inside 'today'
}

0
投票

我正在为我的数据库对象寻找解决方案,并检查数据库对象中的文件名是否包含“。”如果确实如此,则意味着所有图像上传检查都成功,然后不显示 div 错误。

<?PHP
 } else if ( str_contains('$gigObject->getPhoto()','.' ) !== false) {
   ?>
  <div class="bottom" id="photoHeaderError" style="display:block">
    <div class="bottom_error_alert">
     Image is missing. Please upload one for your gig.
    </div>

  </div>

  <?php
    }
?>

0
投票

最干净的方法是否定 str_contains 的响应。

if (!str_contains($var, 'something')) {
    // $var does not contain 'something'
}
© www.soinside.com 2019 - 2024. All rights reserved.