考虑一下。
$a = 'How are you?';
if ($a contains 'are')
echo 'true';
假设我有上面的代码,那么语句if ($a contains 'are')
的正确写法是什么?
你可以使用strpos()
函数,用于查找一个字符串在另一个字符串中的出现。
$a = 'How are you?';
if (strpos($a, 'are') !== false) {
echo 'true';
}
注意,使用!==false
是故意的(无论是!=false
还是===true
都不会返回所需的结果);strpos()
返回针状字符串在干草堆字符串中开始的偏移量,如果没有找到针状字符串,则返回布尔值false
。由于0是一个有效的偏移量,而0是 "假的",我们不能使用更简单的结构,如!strpos($a, 'are')
。
你可以使用正则表达式,与其他用户提到的`strpos'相比,它更适合于单词匹配,它也会对诸如 fare, care, stare 等字符串返回 true。这在正则表达式中可以通过使用词的边界简单地避免。
一个简单的are的匹配可以是这样的。
$a = 'How are you?';
if (preg_match('/\bare\b/', $a)) {
echo 'true';
}
在性能方面,strpos
要快三倍,请记住,当我一次做一百万次比较时,preg_match
需要1.5秒才能完成,而strpos
需要0.5秒。
编辑。 为了搜索字符串的任何部分,而不仅仅是逐字搜索,我建议使用正则表达式,如
$a = 'How are you?';
$search = 'are y';
if(preg_match("/{$search}/i", $a)) {
echo 'true';
}
正则表达式末尾的 "i "使正则表达式不区分大小写,如果你不希望这样,你可以省略它。
现在,这在某些情况下可能会有问题,因为$search字符串没有经过任何处理,我的意思是,它在某些情况下可能无法通过检查,因为如果$search
是用户输入的,他们可以添加一些字符串,可能表现得像一些不同的正则表达式...
另外,这里有一个很好的工具,用于测试和查看各种正则表达式的解释Regex101 。
为了将这两组功能结合到一个单一的多用途函数中(包括可选择的大小写敏感性),你可以使用这样的东西。
function FindString($needle,$haystack,$i,$word)
{ // $i should be "" or "i" for case insensitive
if (strtoupper($word)=="W")
{ // if $word is "W" then word search instead of string in string search.
if (preg_match("/\b{$needle}\b/{$i}", $haystack))
{
return true;
}
}
else
{
if(preg_match("/{$needle}/{$i}", $haystack))
{
return true;
}
}
return false;
// Put quotes around true and false above to return them as strings instead of as bools/ints.
}
<?php
$mystring = 'abc';
$findme = 'a';
$pos = strpos($mystring, $findme);
// Note our use of ===. Simply, == would not work as expected
// because the position of 'a' was the 0th (first) character.
if ($pos === false) {
echo "The string '$findme' was not found in the string '$mystring'.";
}
else {
echo "The string '$findme' was found in the string '$mystring',";
echo " and exists at position $pos.";
}
?>