我正面临一个问题....请帮助我......
我有2个字符串:
$teamslist = BAL@DET,WAS@SF,LA@STL,LAA@KC;
$string = BAL,WAS,LA,LAA,DET,SF,STL,KC;
我想要的是检查$ string是$ teamslist中的元素,而不是在$ teamslist中显示整个名称......
e.g:
我在$ 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'];
}
}
请帮助我....
答案 0 :(得分:1)
在这种情况下你也可以使用 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);
答案 1 :(得分:1)
您可以使用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)
答案 2 :(得分:1)
$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"
}
}
值是数组,以防万一团队中有相同的部分。