php 将字符串数组与字符串进行比较

php compare array of string to string

假设我有字符串

$string = "12315";

我想比较这个数组并想要这样的结果:

$arr = [
   "123", //should be true
   "115", //should be true 
   "111", //false
   "132", //true
   "1512" //true
   "5531" //false
] 

数组值的每个计数不应大于给定的字符串 我应该怎么做?提前致谢!

foreach($array as $string)
{
  if(strpos($searchstring, $string) !== false) 
  {
    echo 'yes its in here';
    break;
  }
}

使用array_map函数:

$string = '...';
$arr = ['..', '.', '..,', '....']; // true, true, false, false
function check($str) { 
    /* Implement your check here */
    /* Smthng like: */
    $a = $string;
    foreach ($i = 0; $i<strlen($str); $i++) {
        $index = strpos($a, $str[$i]);
        if ($index === false) return false;
        else substr_replace($a,'', $index, 1);
    }
    return true;
}
$result = array_map(check, $arr);

首先你创建一个可能的组合然后你比较!

试试这个!

function create_possible_arrays(&$set, &$results)
    {
        for ($i = 0; $i < count($set); $i++)
        {
            $results[] = $set[$i];
            $tempset = $set;
            array_splice($tempset, $i, 1);
            $tempresults = array();
            create_possible_arrays($tempset, $tempresults);
            foreach ($tempresults as $res)
            {
                $results[] = $set[$i] . $res;
            }
        }
    }
    $results = array();
    $str = '12315'; //your input string
    $str = str_split($str); //create array
    create_possible_arrays($str, $results);
    $inputs = array(
        "123", //should be true
        "115", //should be true
        "111", //false
        "132", //true
        "1512", //true
       "5531"
    );
    foreach($inputs as $input){
        if(in_array($input,$results)){
            echo $input.' true <br/>';
        }else{
            echo $input.' false <br/>';
        }
    }

your result:

    123 true
    115 true
    111 false
    132 true
    1512 true
    5531 false
<?php
$string = "12315";
$arr = ["123", "115", "111", "132", "1512", "5531"];

function specialCmp($str, $val) {
    for($i=0; $i<strlen($val); $i++) {
        $pos = strpos($str, $val[$i]);
        if($pos !== false)
            $str = substr_replace($str, '', $pos, 1);
        else return false;
    }
    return true;
}

$out = array();
foreach($arr as $val)
    $out[] = specialCmp($string, $val);

echo '<pre>';
var_dump($out);
echo '</pre>';
?>

试试这个:

$string = "123115";
$arr = [
   "123",
   "115", 
   "111",
   "132",
   "1512",
   "5531"
];

$varr = array_filter($arr, function($el) use ($string) {
        return ( stristr($string,$el, true)!==false);
    });
print_r($varr);