给定
$str=array( "Chelsea 0-5 MAN-UNITED",
"Chelsea 0-2 Aston Villa",
"Chelsea 0-3 Pokemon (TRASH i dont want)");
我试图达到的输出:
array(
array('teams'=>'chelsea Vs MAN-UNITED','score'=>'0-5')
array('teams'=>'chelsea Vs Aston Villa','score'=>'0-2')
array('teams'=>'chelsea Vs Pokemon','score'=>'0-3')
);
我目前的方法是使用explore(",$str(;然后移动[0]。'Vs’。[2] 分成小组,[1]分成分数。。
这很好,除非团队名称中有空白,或者((中有额外的文本。
那么这可以使用preg_match来完成吗?
感谢
您可以使用
preg_split('/ ('d+-'d+) /', $str, 3, PREG_SPLIT_DELIM_CAPTURE);
这将把您想要的三个线段放入一个数组中。在上面的第一个例子中:
array(3) {
[0] =>
string(8) "Chelsea"
[1] =>
string(3) "0-5"
[2] =>
string(11) "MAN-UNITED"
}
然后,您可以进一步过滤第一个和第三个结果以清除垃圾。不幸的是,您还没有给出处理垃圾的具体规则。如果一支球队和一个分数之间可能存在垃圾,除非你知道自己在寻找什么,否则很难把它弄出来。我也不确定'd+-'d+
是否可以出现在字符串中除分数之外的任何位置。
另一种可能性是
preg_match('/([a-z'.'s]+)('d+-'d+)([a-z'.'s]+)/i', $str, $matches);
其将这三个项目存储在CCD_ 2中并去除垃圾。然而,它不允许在团队名称中使用数字,也不修剪尾部/前导空格。
试试这个:
$str=array( "Chelsea 0-5 MAN-UNITED",
"Chelsea 0-2 Aston Villa",
"Chelsea 0-3 Pokemon (TRASH i dont want)");
$arr = array();
$pattern = "/([0-9]+'-[0-9]+)/";
foreach ($str as $sub) {
$parts = preg_split($pattern, $sub, -1, PREG_SPLIT_DELIM_CAPTURE);
if (count($parts) == 3) {
$team1 = trim(preg_replace("/'(.*'Z/", "", $parts[0]));
$score = trim($parts[1]);
$team2 = trim(preg_replace("/'(.*'Z/", "", $parts[2]));
$teams = "$team1 Vs $team2";
$element = array("teams" => $teams, "score" => $score);
$arr[] = $element;
}
}
print_r($arr);
输入:
$str=array( "Chelsea 0-5 MAN-UNITED",
"Chelsea 0-2 Aston Villa",
"Chelsea 0-3 Pokemon (TRASH i dont want)");
输出:
Array
(
[0] => Array
(
[teams] => Chelsea Vs MAN-UNITED
[score] => 0-5
)
[1] => Array
(
[teams] => Chelsea Vs Aston Villa
[score] => 0-2
)
[2] => Array
(
[teams] => Chelsea Vs Pokemon
[score] => 0-3
)
)
它在这里发挥作用:http://eval.in/14236
哦,请确保您至少使用了PHP 4.0.5。PREG_SPLIT_DELIM_CAPTURE
就是在那时推出的。