如何使用PHP匹配字母并检查数组内是否存在该值

时间:2017-04-29 06:49:38

标签: php arrays

我需要一个帮助。我需要检查字符串是否存在于数组内部,并且它应该使用PHP搜索字母。我在下面解释我的代码。

$resultArr=array("9937229853","9937229856","9937229875");
$searchValue="+919937229853";

这里我需要检查$searchValue中的某些值是否存在于数组内部。我在做如下,但它没有给我正确的结果。

$searchValue="+919937229853";
$resultArr=array("9937229853","9937229856","9937229875");
if(!in_array($searchValue, $resultArr))
{
 $flag=1;
}else{
  $flag=0;
}
echo $flag;

根据我的要求,此结果应打印1,因为来自$searchValue的某些值也会出现在该数组中,但回显结果将来0。请帮助我。

5 个答案:

答案 0 :(得分:0)

您可以尝试以下代码。

if(!in_array(substr($searchValue,-10), $resultArr))

答案 1 :(得分:0)

如果

,则下面的函数将返回true
  • 您的$searchValue位于数组(in_array)或
  • 如果数组的任何项是$searchValue的子字符串 换句话说:如果$searchValue的一部分在数组中。

这是代码以及您如何称呼它:

function search($needle, $haystack) {
    // is $needle contained in the array as it is?
    if (in_array($needle, $haystack))
        return true;

    // Is any part of $needle part of the array?
    foreach ($haystack as $value) {
        if (strpos($needle, $value) !== FALSE)
            return true;
    }

    return false;
}

$resultArr = array("9937229853", "9937229856", "9937229875");
$searchValue = "+919937229853";

$result = search($searchValue, $resultArr);
var_dump($result);

答案 2 :(得分:0)

$searchValue="+919937229853";
$searchValue = str_replace("+91","",$searchValue);
$resultArr=array("9937229853","9937229856","9937229875");
if(in_array($searchValue, $resultArr))
{
 $flag=1;
}else{
  $flag=0;
}
echo $flag;

用户str_replace函数从字符串

替换前三个字符

答案 3 :(得分:0)

$flag=0;
for($i=0;$i<strcmp($searchValue);$i++){
    for($j=0;$j<strcmp($searchValue);$j++){
         $part=substr($searchValue,$i,$j)
         array_filter($resultArr, function($el) use ($part) {
             if ( strpos($el, $part) !== false ){
                  $flag=1;
             }
         });
    }
}

答案 4 :(得分:0)

$searchValue="+919937229853";
$resultArr=array("9937229853","9937229856","9937229875");

foreach($resultArr as $value)
{
    if(strpos($value,$searchValue) || strpos($searchValue,$value) || $searchValue==$value)
    {
        $flag = 1;
        break;
    }
    else
        $flag=0;
}
echo $flag;

I think this will do what you are looking for. in_array() method search string in array but for the exact string. strpos can search substring in long string and return the offset number or the index of substring in the long string.