显示组合列表的问题


Issue with displaying a combined list

我面临一个问题。。。。请帮帮我…

我有两个字符串:

$teamslist = BAL@DET,WAS@SF,LA@STL,LAA@KC;
$string = BAL,WAS,LA,LAA,DET,SF,STL,KC;

我想检查的是$string元素是否在$teamslist中找到,而不是它在$teams list中显示整个名称。。。

例如:

我在$string中有"BAL",我想检查它是否在$teamlist中找到。。。如果找到,结果应该是

$result will be = BAL@DET

我使用的代码适用于一个条件,但不适用于第二个条件。。。如果在@符号之前发现BAL,则显示正确的结果。。但如果在@符号后找到它,它有时会显示一个字母或什么都不显示。。请帮我解决第二个问题。。。若单词在@符号之前或之后,它将显示两者的正确结果。。。

希望这能理解我的问题。。我正在尝试的代码是:

foreach($string as $tag)
{                               
        $teamslisto = substr($teamslist, strpos($teamslist, $tag)+strlen($tag));
        $teamslisto2 = substr($teamslist, strpos($teamslist, $tag) - strlen($tag) -1);
        $final=explode(",",$teamslisto);
        $final2=explode(",",$teamslisto2);
            if($final['0']=="")
            {
                $opkplay = $final2['0'];
            }
            else 
            {
                $opkplay = $tag.$final['0'];
            }
}

请帮帮我…

在这种情况下,您也可以使用stripos()

修正:条纹可能会使虚假的比赛爆发球队,而不是在阵列中。

$teamslist = 'BAL@DET,WAS@SF,LA@STL,LAA@KC';
$string = 'BAL,WAS,LA,LAA,DET,SF,STL,KC';
$teamslist = explode(',', $teamslist);
$string = explode(',', $string);
$result = array();
foreach($string as $tag) {
    foreach($teamslist as $teams) {
        $temp = explode('@', $teams);
        if(in_array($tag, $temp)) {
            $result[$tag] = $teams;
        }
    }
}
echo '<pre>';
print_r($result);

您可以使用preg_match():进行尝试

$teamslist = 'BAL@DET,WAS@SF,LA@STL,LAA@KC,FOO@BAR';
$string = 'BAL,WAS,LA,LAA,DET,SF,STL,KC';
$persons = explode(',', $string);
$result = array();
foreach($persons as $person) {
    if(preg_match('/' . $person . '@[^@,]+|[^@,]+@' . $person . '/', $teamslist, $match) === 0)
        continue;
    if(in_array($match[0], $result) === false)
        $result[] = $match[0];
}
var_dump($result);

这将导致:

array (size=4)
  0 => string 'BAL@DET' (length=7)
  1 => string 'WAS@SF' (length=6)
  2 => string 'LA@STL' (length=6)
  3 => string 'LAA@KC' (length=6)
$teamslist = "BAL@DET,WAS@SF,LA@STL,LAA@KC";
$string = "BAL,WAS,LA,LAA,DET,SF,STL,KC";

$strings = explode(',', $string);
$result = array();
foreach($strings as $str)
{ 
  $escaped = preg_quote($str); // just in case..
  if (preg_match_all('/(^|,)([^@]+@' . $escaped. '|' . $escaped . '@[^@]+)($|,)/iU',
                     $teamslist, $matches))
    $result[$str] = $matches[2];
}
var_dump($result);

结果

array(8) {
  ["BAL"]=>
  array(1) {
    [0]=>
    string(7) "BAL@DET"
  }
  ["WAS"]=>
  array(1) {
    [0]=>
    string(6) "WAS@SF"
  }
  ["LA"]=>
  array(1) {
    [0]=>
    string(6) "LA@STL"
  }
  ["LAA"]=>
  array(1) {
    [0]=>
    string(6) "LAA@KC"
  }
  ["DET"]=>
  array(1) {
    [0]=>
    string(7) "BAL@DET"
  }
  ["SF"]=>
  array(1) {
    [0]=>
    string(6) "WAS@SF"
  }
  ["STL"]=>
  array(1) {
    [0]=>
    string(6) "LA@STL"
  }
  ["KC"]=>
  array(1) {
    [0]=>
    string(6) "LAA@KC"
  }
}

值是数组,以防有几个团队拥有相同的部分。