考虑:
$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中,验证字符串是否包含某个子字符串的最佳方法是使用一个简单的助手函数,如下所示:
function contains($haystack, $needle, $caseSensitive = false) {
return $caseSensitive ?
(strpos($haystack, $needle) === FALSE ? FALSE : TRUE):
(stripos($haystack, $needle) === FALSE ? FALSE : TRUE);
}
说明:
strpos查找字符串中第一个区分大小写的子字符串的位置。stripos查找字符串中不区分大小写的子字符串第一次出现的位置。myFunction($haystack,$needle)===假?FALSE:TRUE确保myFunction始终返回布尔值,并修复子字符串索引为0时的意外行为。$case敏感?A:B选择strpos或stripos来完成工作,具体取决于$caseSensitive的值。
输出:
var_dump(contains('bare','are')); // Outputs: bool(true)
var_dump(contains('stare', 'are')); // Outputs: bool(true)
var_dump(contains('stare', 'Are')); // Outputs: bool(true)
var_dump(contains('stare', 'Are', true)); // Outputs: bool(false)
var_dump(contains('hair', 'are')); // Outputs: bool(false)
var_dump(contains('aren\'t', 'are')); // Outputs: bool(true)
var_dump(contains('Aren\'t', 'are')); // Outputs: bool(true)
var_dump(contains('Aren\'t', 'are', true)); // Outputs: bool(false)
var_dump(contains('aren\'t', 'Are')); // Outputs: bool(true)
var_dump(contains('aren\'t', 'Are', true)); // Outputs: bool(false)
var_dump(contains('broad', 'are')); // Outputs: bool(false)
var_dump(contains('border', 'are')); // Outputs: bool(false)
其他回答
查看strpos():
<?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.";
}
您可以使用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 ";
}
如果搜索不区分大小写,则使用strstr()或stristr(。
可以通过三种不同的方式完成:
$a = 'How are you?';
1-stristr()
if (strlen(stristr($a,"are"))>0) {
echo "true"; // are Found
}
2-strpos()
if (strpos($a, "are") !== false) {
echo "true"; // are Found
}
3-preg_match()
if( preg_match("are",$a) === 1) {
echo "true"; // are Found
}
使用strstr()和stristr(()从字符串中查找单词出现的另一个选项如下:
<?php
$a = 'How are you?';
if (strstr($a,'are')) // Case sensitive
echo 'true';
if (stristr($a,'are')) // Case insensitive
echo 'true';
?>