在具有拆分变量字母的数组中查找字符串

时间:2014-09-25 16:57:37

标签: php arrays string

$string = 'Ma';

$arr1 = str_split($string);

foreach($arr1 as $a)
{
    echo $a."<br>";
}

$os = array("Mac", "NT", "Irix", "Linux", "apple");

这里我在$string变量中有一些字符串。在此行echo $a."<br>";中,它返回此结果

M
a

它拆分字符串。现在我想找到带有这些拆分字符串(M a)的单词(array("Mac", "NT", "Irix", "Linux", "apple");)。例如,我的字符串是Ma,首先我想在数组中找到字符串,该字符串以M开头,然后我想在数组中找到另一个字符串,其中包含a字符串。然后我想回应这两个字符串。结果应为Mac apple。我怎么得到它?

3 个答案:

答案 0 :(得分:1)

你可以这样做:

$string = 'Ma';
$oses = array("Mac", "NT", "Irix", "Linux", "apple");

foreach (str_split($string) as $first_letter) {
    $fl_array = preg_grep("/^".$first_letter."/", $oses);

    var_dump($fl_array);
}

输出:

array(1) {
  [0]=>
  string(3) "Mac"
}
array(1) {
  [4]=>
  string(5) "apple"
}

答案 1 :(得分:1)

只需循环数组并比较字符串的第一个字母。

$string = 'Ma';
$arr1 = str_split($string);
$os = array("Mac", "NT", "Irix", "Linux", "apple");

foreach($arr1 as $a)
{
    foreach ($os as $o)
    {
       if ($o[0] === $a) 
           echo $o, "<br/>"; // Mac<br/>apple<br/>
    }
}

或者,采用不同的方法:

$string = 'Ma';
$arr1 = str_split($string);
$os = array("Mac", "NT", "Irix", "Linux", "apple");

foreach ($os as $o)
    if(in_array($o[0], $arr1))
       echo $o, "<br/>";

答案 2 :(得分:0)

<?php


    $arr=array("Mac",'apple',"linux");

      foreach($arr as $v){

          if(preg_match("/^M/",$v)){

           echo $v."\n";
      }

       if(preg_match("/^a/",$v)){

           echo $v;
       }
}
?>