考虑:
$a = 'How are you?';
if ($a contains 'are')
echo 'true';
假设我有上面的代码,如果($a包含“are”),写语句的正确方法是什么?
考虑:
$a = 'How are you?';
if ($a contains 'are')
echo 'true';
假设我有上面的代码,如果($a包含“are”),写语句的正确方法是什么?
当前回答
strpos函数工作得很好,但是如果您想对段落中的单词进行不区分大小写的检查,那么可以使用PHP的stripos函数。
例如
$result = stripos("I love PHP, I love PHP too!", "php");
if ($result === false) {
// Word does not exist
}
else {
// Word exists
}
查找字符串中不区分大小写的子字符串第一次出现的位置。
如果字符串中不存在该单词,则返回false,否则返回单词的位置。
其他回答
如果要检查字符串是否包含多个特定单词,可以执行以下操作:
$badWords = array("dette", "capitale", "rembourser", "ivoire", "mandat");
$string = "a string with the word ivoire";
$matchFound = preg_match_all("/\b(" . implode($badWords,"|") . ")\b/i", $string, $matches);
if ($matchFound) {
echo "a bad word has been found";
}
else {
echo "your string is okay";
}
例如,这对于在发送电子邮件时避免垃圾邮件非常有用。
我在这方面遇到了一些麻烦,最后我选择了自己的解决方案。不使用正则表达式引擎:
function contains($text, $word)
{
$found = false;
$spaceArray = explode(' ', $text);
$nonBreakingSpaceArray = explode(chr(160), $text);
if (in_array($word, $spaceArray) ||
in_array($word, $nonBreakingSpaceArray)
) {
$found = true;
}
return $found;
}
您可能会注意到,前面的解决方案并不是对另一个用作前缀的单词的答案。为了使用您的示例:
$a = 'How are you?';
$b = "a skirt that flares from the waist";
$c = "are";
对于上面的示例,$a和$b都包含$c,但您可能希望函数告诉您,只有$a包含$c。
您需要使用相同/不相同的运算符,因为strpos可以返回0作为其索引值。如果您喜欢三元运算符,请考虑使用以下运算符(我承认这有点倒退):
echo FALSE === strpos($a,'are') ? 'false': 'true';
您可以使用strstr函数:
$haystack = "I know programming";
$needle = "know";
$flag = strstr($haystack, $needle);
if ($flag){
echo "true";
}
不使用内置功能:
$haystack = "hello world";
$needle = "llo";
$i = $j = 0;
while (isset($needle[$i])) {
while (isset($haystack[$j]) && ($needle[$i] != $haystack[$j])) {
$j++;
$i = 0;
}
if (!isset($haystack[$j])) {
break;
}
$i++;
$j++;
}
if (!isset($needle[$i])) {
echo "YES";
}
else{
echo "NO ";
}
我认为一个好主意是使用mb_stpos:
$haystack = 'How are you?';
$needle = 'are';
if (mb_strpos($haystack, $needle) !== false) {
echo 'true';
}
因为此解决方案区分大小写,并且对所有Unicode字符都是安全的。
但你也可以这样做(sauch的回应还没有):
if (count(explode($needle, $haystack)) > 1) {
echo 'true';
}
此解决方案对Unicode字符也区分大小写并安全。
此外,在表达式中不使用否定,这会增加代码的可读性。
以下是使用函数的其他解决方案:
function isContainsStr($haystack, $needle) {
return count(explode($needle, $haystack)) > 1;
}
if (isContainsStr($haystack, $needle)) {
echo 'true';
}