如何通过搜索将字符串放入数组然后输出?

时间:2014-03-24 10:31:27

标签: php regex

$states = "Mississippi Alabama Texas Massachusetts Kansas";
$statesA = explode(' ',$states);
$statesArray = array();

foreach($statesA as $state) {
if(preg_match( '/xas$/', trim($state)))
$statesArray[0] = trim($state);
}

foreach($statesA as $state) {
if(preg_match('/^k.*s$/i', trim($state)))
$statesArray[1] = trim($state);
}

foreach($statesA as $state) {
if(preg_match('/^M.*s$/', trim($state)))
$statesArray[2] = trim($state);
}

foreach($statesA as $state) {
if(preg_match('/a$/', trim($state)))
$statesArray[3] = trim($state);
}

foreach($statesA as $state) { #PROBLEM HERE
if(preg_match('/^M/', trim($state)))
$statesArray[4] = trim($state);
}

foreach ( $statesArray as $element => $value )
print( "Element $element of the Array is $value <br />");

任务是基本上输出一个以变量状态中的字母M开头的单词。我在"Mississippi Alabama Texas Massachusetts Kansas"中有$states。当我尝试将其打印出来时,Massachusetts会被打印出来而不是Mississippi。那是为什么?

1 个答案:

答案 0 :(得分:2)

<?
 foreach($statesA as $state) { #PROBLEM HERE
  if(preg_match('/^M/', trim($state)))
  $statesArray[4] = trim($state);
  }
?>

在上面的代码中,马萨诸塞州和密西西比州都匹配您的表达,并且它们都存储在$statesArray[4]中。如果您只想要第一场比赛,也许您还应该检查是否已设置$statesArray[4]。所以,这样的事情应该有效:

<?
  foreach($statesA as $state) { #PROBLEM HERE
    if(preg_match('/^M/', trim($state)) && !isset($statesArray[4]))
    $statesArray[4] = trim($state);
  }
?>

仅当$statesArray[4]尚未设置时才会填充{{1}}。

请告诉我这是否适合您。