如何获取包含匹配字符串值的字符串列表?
让我试着解释一下。
这是我的输入字符串(整个事情是一个字符串):
你向左移动了55个空格。你已经移动了23个空格。你向左移动了71个空格。你跳了起来。你向左移动了两个空格。你向左移动了88个空格。你跳了下来。你跳了起来。你已经移动了131个空格。你跳了下来。
我想要的是获取所有移动方向及其空格数的列表。所以,我必须搜索字符串并查找所有'你已经移动[方向] [numspaces]空格。并以某种方式将[方向]存储到列表中,将[numspaces]存储到另一个列表中。
所以,最后,我的方向列表将包含:
左
右
左
左
右
我的numspaces列表将包含:
55
23个
71个
2
131
我该怎么办?
答案 0 :(得分:2)
$str = 'You have moved left 55 spaces. You have moved right 23 spaces. You have moved left 71 spaces. You have jumped up. You have moved left 2 spaces. You have moved left 88 spaces. You have jumped down. You have jumped up. You have moved right 131 spaces. You have jumped down.';
$directions = array('left', 'right');
$directions_regex = implode('|', array_map('preg_quote', $directions));
preg_match_all("~($directions_regex)\s+(\d+)~", $str, $matches);
var_dump($matches);
答案 1 :(得分:1)
代码:
$str = 'You have moved left 55 spaces. You have moved right 23 spaces. You have moved left 71 spaces. You have jumped up. You have moved left 2 spaces. You have moved left 88 spaces. You have jumped down. You have jumped up. You have moved right 131 spaces. You have jumped down.';
preg_match_all('/You have moved (left|right) (\d+) spaces/', $str, $matches);
array_shift($matches);
print_r($matches);
结果:
Array ( [0] => Array ( [0] => left [1] => right [2] => left [3] => left [4] => left [5] => right ) [1] => Array ( [0] => 55 [1] => 23 [2] => 71 [3] => 2 [4] => 88 [5] => 131 ) )