考虑:

$a = 'How are you?';

if ($a contains 'are')
    echo 'true';

假设我有上面的代码,如果($a包含“are”),写语句的正确方法是什么?


当前回答

也许你可以这样做:

<?php
    findWord('Test all OK');

    function findWord($text) {
        if (strstr($text, 'ok')) {
            echo 'Found a word';
        }
        else
        {
            echo 'Did not find a word';
        }
    }
?>

其他回答

您应该使用不区分大小写的格式,因此如果输入的值是小写或大写,则无所谓。

<?php
$grass = "This is pratik joshi";
$needle = "pratik";
if (stripos($grass,$needle) !== false) { 

 /*If i EXCLUDE : !== false then if string is found at 0th location, 
   still it will say STRING NOT FOUND as it will return '0' and it      
   will goto else and will say NOT Found though it is found at 0th location.*/
    echo 'Contains word';
}else{
    echo "does NOT contain word";
}
?>

在这里,stripos在不考虑箱子(小/帽)的情况下,在heystack中找到了针头。

带输出的PHPCode样本

现在,使用PHP 8,您可以使用str_contains执行此操作:

if (str_contains('How are you', 'are')) { 
    echo 'true';
}

RFC

PHP 8之前

您可以使用strpos()函数,该函数用于查找一个字符串在另一个字符串中的出现:

$haystack = 'How are you?';
$needle   = 'are';

if (strpos($haystack, $needle) !== false) {
    echo 'true';
}

请注意,使用!==false是故意的(!=false或==true都不会返回期望的结果);strpos()返回大海捞针字符串开始时的偏移量,如果找不到针,则返回布尔值false。由于0是有效的偏移量,0是“false”,因此我们不能使用更简单的构造,如!strpos($a,'are')。

如果搜索不区分大小写,则使用strstr()或stristr(。

我有点印象深刻,这里没有一个使用strpos、strstr和类似函数的答案提到多字节字符串函数(2015-05-08)。

基本上,如果您在查找某些语言(如德语、法语、葡萄牙语、西班牙语等)特定字符的单词时遇到困难(例如:ä,é,ô,ç,º,ñ),您可能需要在函数前面加上mb_。因此,接受的答案将使用mb_strpos或mb_stripos(用于不区分大小写的匹配):

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

如果不能保证所有数据都是100%的UTF-8格式,则可能需要使用mb_函数。

乔尔·斯波尔斯基(Joel Spolsky)的一篇很好的文章解释了为什么每个软件开发人员都必须了解Unicode和字符集(没有借口!)。

使用strstr()和stristr(()从字符串中查找单词出现的另一个选项如下:

<?php
    $a = 'How are you?';
    if (strstr($a,'are'))  // Case sensitive
        echo 'true';
    if (stristr($a,'are'))  // Case insensitive
        echo 'true';
?>