2016-04-28 87 views
1
<?php 

$string = "String is '@Name Surname test @Secondname Surname tomas poas tomas'" 

preg_match_all("/@(\w+)(\s)(\w+)/", $string, $matches); 

我想摘录:preg_match_all返回的结果太多

[ 
0 => '@Name Surname', 
1 => '@Secondname Surname', 
] 

我得到什么;

array (
    0 => 
    array (
    0 => '@Name Surname', 
    1 => '@Secondname Surname', 
), 
    1 => 
    array (
    0 => 'Name', 
    1 => 'Secondname', 
), 
    2 => 
    array (
    0 => ' ', 
    1 => ' ', 
), 
    3 => 
    array (
    0 => 'Surname', 
    1 => 'Surname', 
), 
) 
+0

这就是'preg_match_all()'的工作原理。 1 subArray =整个匹配,2subArray 1捕获组,3subArray 2捕获组,... – Rizier123

回答

3

这就是preg_match_all()和捕获组的工作方式。

如果你只是想要所有的名字,你需要减少到只需要或使用非捕获括号。

例如:

preg_match_all("/(@\w+\s\w+)/", $string, $matches); 

。注意,通过默认值:

结果排序使得$ matches [0]被满图案的阵列 匹配,则$匹配1是阵列由第一个 加括号的子模式匹配的字符串,依此类推。

所以,你真的不需要你的情况来捕捉任何东西:

preg_match_all("/@\w+\s\w+/", $string, $matches); 
2

使用此表达式(除去捕获组空格)

/@\w+\s\w+/ 

测试在这里:

https://regex101.com/r/cL5xH2/2

结果:

[ 
0 => '@Name Surname', 
1 => '@Secondname Surname', 
]