考虑:
$a = 'How are you?';
if ($a contains 'are')
echo 'true';
假设我有上面的代码,如果($a包含“are”),写语句的正确方法是什么?
考虑:
$a = 'How are you?';
if ($a contains 'are')
echo 'true';
假设我有上面的代码,如果($a包含“are”),写语句的正确方法是什么?
当前回答
您应该使用不区分大小写的格式,因此如果输入的值是小写或大写,则无所谓。
<?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样本
其他回答
如果搜索不区分大小写,则使用strstr()或stristr(。
另一个选项是使用strstr()函数。类似于:
if (strlen(strstr($haystack,$needle))>0) {
// Needle Found
}
注意:strstr()函数区分大小写。对于不区分大小写的搜索,请使用stristr()函数。
检查字符串是否包含特定单词?
这意味着字符串必须解析为单词(请参见下面的注释)。
执行此操作并指定分隔符的一种方法是使用preg_split(doc):
<?php
function contains_word($str, $word) {
// split string into words
// separators are substrings of at least one non-word character
$arr = preg_split('/\W+/', $str, NULL, PREG_SPLIT_NO_EMPTY);
// now the words can be examined each
foreach ($arr as $value) {
if ($value === $word) {
return true;
}
}
return false;
}
function test($str, $word) {
if (contains_word($str, $word)) {
echo "string '" . $str . "' contains word '" . $word . "'\n";
} else {
echo "string '" . $str . "' does not contain word '" . $word . "'\n" ;
}
}
$a = 'How are you?';
test($a, 'are');
test($a, 'ar');
test($a, 'hare');
?>
跑一次就可以
$ php -f test.php
string 'How are you?' contains word 'are'
string 'How are you?' does not contain word 'ar'
string 'How are you?' does not contain word 'hare'
注意:这里我们不是指每个符号序列的单词。
单词的实际定义是PCRE正则表达式引擎,其中单词是仅由单词字符组成的子字符串,由非单词字符分隔。
“单词”字符是任何字母、数字或下划线字符,也就是说,可以是Perl“单词”一部分的任何字符。这个字母和数字的定义由PCRE的字符控制表,如果正在进行特定于区域设置的匹配,则可能会有所不同(..)
我有点印象深刻,这里没有一个使用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和字符集(没有借口!)。
虽然这些答案中的大多数都会告诉你字符串中是否出现了子字符串,但如果你要查找的是一个特定的单词,而不是子字符串,那么这通常不是你想要的。
有什么不同?子字符串可以出现在其他单词中:
“area”开头的“are”“野兔”末尾的“are”“are”位于“fare”的中间
缓解这种情况的一种方法是使用正则表达式和单词边界(\b):
function containsWord($str, $word)
{
return !!preg_match('#\\b' . preg_quote($word, '#') . '\\b#i', $str);
}
这种方法没有上面提到的假阳性,但它有自己的一些边缘情况。单词边界与非单词字符(\W)匹配,这些字符将是非a-z、a-z、0-9或_的任何字符。这意味着数字和下划线将被计算为单词字符,类似这样的场景将失败:
“你在想什么?”中的“是”“哦,你不知道那些是4吗?”
如果你想要比这更准确的东西,你必须开始进行英语语法分析,这是一个相当大的蠕虫(而且假设语法使用正确,但这并不总是给定的)。