Php 提取字符串上的每个匹配项
我有一个字符串,格式是“a-b”、“c-d”、“e-f”… 使用Php 提取字符串上的每个匹配项,php,regex,preg-match,preg-match-all,Php,Regex,Preg Match,Preg Match All,我有一个字符串,格式是“a-b”、“c-d”、“e-f”… 使用preg_match,我如何提取它们并获得如下数组: Array ( [0] =>a-b [1] =>c-d [2] =>e-f ... [n-times] =>xx-zz ) 谢谢您可以: $str = '"a-b""c-d""e-f"'; if(preg_match_all('/"(.*?)"/',$str,$m)) { var_dump($m[1]);
preg_match
,我如何提取它们并获得如下数组:
Array
(
[0] =>a-b
[1] =>c-d
[2] =>e-f
...
[n-times] =>xx-zz
)
谢谢您可以:
$str = '"a-b""c-d""e-f"';
if(preg_match_all('/"(.*?)"/',$str,$m)) {
var_dump($m[1]);
}
输出:
array(3) {
[0]=>
string(3) "a-b"
[1]=>
string(3) "c-d"
[2]=>
string(3) "e-f"
}
这是我的看法
$string = '"a-b""c-d""e-f"';
if ( preg_match_all( '/"(.*?)"/', $string, $matches ) )
{
print_r( $matches[1] );
}
以及模式的分解
" // match a double quote
( // start a capture group
. // match any character
* // zero or more times
? // but do so in an ungreedy fashion
) // close the captured group
" // match a double quote
查看
$matches[1]
而不查看$matches[0]
的原因是preg\u match\u all()
在索引1-9中返回每个捕获的组,而整个模式匹配在索引0处。由于我们只需要捕获组(在本例中为第一个捕获组)中的内容,因此我们研究$matches[1]
Regexp并不总是最快的解决方案:
$string = '"a-b""c-d""e-f""g-h""i-j"';
$string = trim($string, '"');
$array = explode('""',$string);
print_r($array);
Array ( [0] => a-b [1] => c-d [2] => e-f [3] => g-h [4] => i-j )
您可以使用
trim($string,“”)
而不是substr()
两次。或者可以使用substr($string,1,strlen($string)-2)
从第二个字符转换为倒数第二个字符。谢谢大家!非常好的输入!