考虑:
$a = 'How are you?';
if ($a contains 'are')
echo 'true';
假设我有上面的代码,如果($a包含“are”),写语句的正确方法是什么?
考虑:
$a = 'How are you?';
if ($a contains 'are')
echo 'true';
假设我有上面的代码,如果($a包含“are”),写语句的正确方法是什么?
当前回答
如果要避免“虚假”和“真实”问题,可以使用subst_count:
if (substr_count($a, 'are') > 0) {
echo "at least one 'are' is present!";
}
它比strpos慢一点,但它避免了比较问题。
其他回答
更简单的选择:
return ( ! empty($a) && strpos($a, 'are'))? true : false;
Use:
$a = 'How are you?';
if (mb_strpos($a, 'are')) {
echo 'true';
}
它执行多字节安全strpos()操作。
下面的功能也起作用,不依赖于任何其他功能;它只使用本机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
另一个选项是使用strstr()函数。类似于:
if (strlen(strstr($haystack,$needle))>0) {
// Needle Found
}
注意:strstr()函数区分大小写。对于不区分大小写的搜索,请使用stristr()函数。
您还可以使用内置函数strchr()和strrchr()以及多字节字符串mb_strchr(()和mb_strrchr(()的扩展。这些函数返回部分字符串,如果找不到,则返回FALSE。
strchr()-查找字符串的第一次出现(是strstr()的别名)。strrchr()-查找字符串中最后出现的字符。