如何将没有空格的用户输入与PHP中具有空白元素的数组相匹配?

时间:2015-07-31 15:53:11

标签: php arrays regex

我们说我的数组[Table Tennis, Basketball, Swimming, ...]中有tabletennis,用户输入为$q,我怎样才能使它匹配?

这是我目前所拥有的,$skills是用户输入,if (preg_grep("/$q/i", $skills)){ $skill = implode(" ", preg_grep("/$q/i", $skills)); $searchRows[$key]['skills'] = '<a href="javascript:void(0)" class="label label-info">' . $skill . '</a>'; }else{ $searchRows[$key]['skills'] = count($skills) . ' skills'; } 是我的数组:

{{1}}

感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

我希望,strtolower ( string $string );str_replace(' ', '', $string);可以为您提供帮助。

示例:

$text = "Table Tennis s";    
$uinput = "tabletennis";    
$withoutwhitespace = str_replace(' ', '', $text);
$strarray = strtolower ($withoutwhitespace);
if($uinput == $strarray) {
  echo " Fine ";
} else {
  echo " Not Fine ";
}

答案 1 :(得分:0)

也许您可以使用更简单的解决方案?

    <?php
$testArray = array("Table Tennis", "Cooking", "Swimming"); //array to test
$testtoArray = array("tabletennis", "cooking", "swi mming");//array to test against
foreach($testArray as $arrVal)
{
    $arrValExploded = explode(" ", $arrVal);
    $var = "";
    for($i=0;$i<=(count($arrValExploded)-1);$i++)
    {
        $var = $var . lcfirst($arrValExploded[$i]);
    }
    if(in_array($var,$testtoArray))
    {
        echo $arrVal . "<br>"; //using this you can get the value from $testArray
        for($i=0;$i<count($testtoArray);$i++)
        {
            if($var == $testtoArray[$i])
            {
                echo $var . "<br>";
            }
        }
    }
    else
    {
        echo "$arrVal didn't match <br>";
    }
}

?>

这适用于任意数量的空间。 示例: - “这是游戏”与“ thisisagame ”匹配。