考虑:
$a = 'How are you?';
if ($a contains 'are')
echo 'true';
假设我有上面的代码, if ($a contains 'are')
,写语句的正确方法if ($a contains 'are')
什么?
#1楼
另一种选择是使用strstr()函数。 就像是:
if (strlen(strstr($haystack,$needle))>0) {
// Needle Found
}
注意点:strstr()函数区分大小写。 对于不区分大小写的搜索,请使用stristr()函数。
#2楼
如果要避免出现“假”和“真实”问题,可以使用substr_count:
if (substr_count($a, 'are') > 0) {
echo "at least one 'are' is present!";
}
它比strpos慢一点,但是避免了比较问题。
#3楼
以下功能也可以使用,并且不依赖于任何其他功能; 它仅使用本机PHP字符串操作。 就个人而言,我不建议这样做,但是您可以看到它是如何工作的:
<?php
if (!function_exists('is_str_contain')) {
function is_str_contain($string, $keyword)
{
if (empty($string) || empty($keyword)) return false;
$keyword_first_char = $keyword[0];
$keyword_length = strlen($keyword);
$string_length = strlen($string);
// case 1
if ($string_length < $keyword_length) return false;
// case 2
if ($string_length == $keyword_length) {
if ($string == $keyword) return true;
else return false;
}
// case 3
if ($keyword_length == 1) {
for ($i = 0; $i < $string_length; $i++) {
// Check if keyword's first char == string's first char
if ($keyword_first_char == $string[$i]) {
return true;
}
}
}
// case 4
if ($keyword_length > 1) {
for ($i = 0; $i < $string_length; $i++) {
/*
the remaining part of the string is equal or greater than the keyword
*/
if (($string_length + 1 - $i) >= $keyword_length) {
// Check if keyword's first char == string's first char
if ($keyword_first_char == $string[$i]) {
$match = 1;
for ($j = 1; $j < $keyword_length; $j++) {
if (($i + $j < $string_length) && $keyword[$j] == $string[$i + $j]) {
$match++;
}
else {
return false;
}
}
if ($match == $keyword_length) {
return true;
}
// end if first match found
}
// end if remaining part
}
else {
return false;
}
// end for loop
}
// end case4
}
return false;
}
}
测试:
var_dump(is_str_contain("test", "t")); //true
var_dump(is_str_contain("test", "")); //false
var_dump(is_str_contain("test", "test")); //true
var_dump(is_str_contain("test", "testa")); //flase
var_dump(is_str_contain("a----z", "a")); //true
var_dump(is_str_contain("a----z", "z")); //true
var_dump(is_str_contain("mystringss", "strings")); //true
#4楼
if (preg_match('/(are)/', $a)) {
echo 'true';
}
#5楼
通过stripos()
使用不区分大小写的匹配 :
if (stripos($string,$stringToSearch) !== false) {
echo 'true';
}
#6楼
使用strstr()和stristr()从字符串中查找单词出现的另一种选择如下:
<?php
$a = 'How are you?';
if (strstr($a,'are')) // Case sensitive
echo 'true';
if (stristr($a,'are')) // Case insensitive
echo 'true';
?>
#7楼
我对此有些麻烦,最后我选择创建自己的解决方案。 不使用正则表达式引擎:
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
。
#8楼
如果只想检查一个字符串是否包含在另一个字符串中,请不要使用p