我有这段代码:
$arr = array("Hello_backup","World!","Beautiful_backup","Day!");
if(in_array("backup", $arr)){
echo "Da";
} else { echo "Nu";
}
但是没有工作因为,in_array指令检查数组中是否存在完整字符串“backup”,这不存在。我需要检查字符串的一部分,例如,返回true,因为backup是其中的一部分“Hello_backup”和“Beautiful_backup”字符串
编辑:我接受了建议,我使用了像这样的stripos:
$arr = array("Hello_backup-2014","World!","Beautiful_backup-2014","Day!");
$word='backup';
if(stripos($arr,$word) !== false){
echo "Da";
} else { echo "Nu";}
但是现在我得到一个错误:“stripos()期望参数1是字符串,在if中给出数组(stripos($ arr,$ word)!== false){”
答案 0 :(得分:1)
在这种情况下,您需要使用stripos()
。例如:
$arr = array("Hello_backup","World!","Beautiful_backup","Day!");
$needle = 'backup';
function check($haystack, $needle) {
foreach($haystack as $word) {
if(stripos($word, $needle) !== false) {
return 'Da!'; // if found
}
}
return 'Nu'; // if not found
}
var_dump(check($arr, $needle));
没有功能:
$arr = array("Hello_backup","World!","Beautiful_backup","Day!");
$found = false;
foreach($arr as $word) {
if(stripos($word, 'backup') !== false) {
$found = true;
break;
}
}
if($found) {
echo 'Da!';
} else {
echo 'Nu';
}
答案 1 :(得分:1)
使用此方法。使用起来有点简单。
$matches = preg_grep('/backup/', $arr);
$keys = array_keys($matches);
print_r($matches);
根据你的问题
$matches = preg_grep('/backup/', $arr);
$keys = array_keys($matches);
$matches = trim($matches);
if($matches != '')
{echo "Da";
}else { echo "Nu";}
答案 2 :(得分:1)
使用implode基本上将数组值连接为字符串,然后使用strpos检查字符串中的字符串。
传递给implode的第一个参数用于分隔数组中的每个值。
$array = array("Hello_backup","World!","Beautiful_backup","Day!");
$r = implode(" ", $array);
if (strpos($r, "backup") !== false) {
echo "found";
}
答案 3 :(得分:1)
<?php
$arr = array("Hello_backup","World!","Beautiful_backup","Day!");
foreach($arr as $arr1) {
if (strpos ($arr1,"backup")) {
echo "Da";
} else {
echo "Nu";
}
}
?>
答案 4 :(得分:1)
尝试使用strpos()
$arr = array("Hello_backup","World!","Beautiful_backup","Day!");
foreach($arr as $v){
echo (strpos($v,"backup")!== false ? "Da" : "Nu");
}
输出: - DaNuDaNu
答案 5 :(得分:1)
以下是适合您的一线解决方案。
$arr = array("Hello_backup-2014","World!","Beautiful_backup-2014","Day!");
$returned_a = array_map(function($u){ if(stripos($u,'backup') !== false) return "Da"; else return "Nu";}, $arr);
您可以将$ returned_a与数组一起用作答案。
Array ( [0] => Da [1] => Nu [2] => Da [3] => Nu )