$search=array("<",">","!=","<=",">=")
$value="name >= vivek ";
我想检查$ value是否包含$ search数组的任何值。我可以找到使用foreach和strpos函数。如果不使用foreach,我还能找到答案吗?如果是这样,请帮助我解决这个问题。
答案 0 :(得分:2)
爆炸$value
并将其转换为数组,然后在php中使用array_intersect()
函数检查字符串是否不包含数组的值。使用下面的代码
<?php
$search=array("<",">","!=","<=",">=");
$value='name >= vivek ';
$array = explode(" ",$value);
$p = array_intersect($search,$array);
$errors = array_filter($p);
//Check if the string is not empty
if(!empty($errors)){
echo "The string contains an value of array";
}
else
{
echo "The string does not containe the value of an array";
}
?>
在此处测试代码http://sandbox.onlinephpfunctions.com/code/7e65faf808de77036a83e185050d0895553d8211
希望这有助于你
答案 1 :(得分:0)
是的,但它需要您重新构建代码。
$search = array("<" => 0, ">" => 1,"!=" => 2,"<=" => 3,">=" => 4);
$value = "name => vivek ";
$value = explode(" ", $value);
foreach($value as $val) {
// search the array in O(1) time
if(isset($search[$val])) {
// found a match
}
}
答案 2 :(得分:0)
使用array_map()和array_filter()
function cube($n)
{
$value="name => vivek ";
return strpos($value, $n);
//return($n * $n * $n);
}
$a = array("<",">","!=","<=",">=");
$value="name => vivek ";
$b = array_map("cube", $a);
print_r($b);
$b = array_filter($b);
print_r($b);
答案 3 :(得分:0)
$search = array("<",">","!=","<=",">=");
$value="name => vivek ";
foreach($value as $searchval) {
if(strpos($value, $searchval) == false)
{
echo "match not found";
}
else
{
echo "match found";
}
}
答案 4 :(得分:0)
这是使用array_reduce的解决方案:
<?PHP
function array_in_string_callback($carry, $item)
{
list($str, $found) = $carry;
echo $str . " - " . $found . " - " . $str . " - " . $item . "<br/>";
$found |= strpos($str, $item);
return array($str, (boolean) $found);
}
function array_in_string($haystack, $needle)
{
$retVal = array_reduce($needle, "array_in_string_callback", array($haystack, false));
return $retVal[1];
}
$search=array("<",">","!=","<=",">=");
$value="name >= vivek ";
var_dump(array_in_string($value, $search));
?>
答案 5 :(得分:0)
我的第一个倾向是使用array_walk()和回调来解决问题,如下所示:
<?php
$search=array("<",">","!=","<=",">=");
$value = "name >= vivek ";
function test($item, $key, $str)
{
if( strpos($str, $item) !== FALSE ) {
echo "$item found in \"$str\"\n";
}
}
array_walk($search, 'test', $value);
// output:
> found in "name >= vivek "
>= found in "name >= vivek "
虽然这解决了没有foreach循环的问题,但它用&#34;什么&#34;来回答问题。而不是&#34;是/否&#34;响应。以下代码直接回答了问题,并允许回答&#34;什么&#34;如下:
<?php
function test($x)
{
$value="name >= vivek ";
return strpos($value, $x);
}
$search = array("<",">","!=","<=",">=");
$chars = array_filter( $search, "test" );
$count = count($chars);
echo "Are there any search chars? ", $answer = ($count > 0)? 'Yes, as follows: ' : 'No.';
echo join(" ",$chars);
// output:
Are there any search chars? Yes, as follows: > >=
如果回复是否定的,则输出为“否”。然后是一个空白区域。
与第一种解决方案相比,第二种解决方案的主要区别在于,在这种情况下,存在可以操纵的返回结果。如果数组的元素与字符串中的字符匹配,则array_filter将该元素添加到$ chars。新数组的元素计数回答问题,如果希望显示它们,则数组本身包含任何匹配。