Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 提取字符串上的每个匹配项_Php_Regex_Preg Match_Preg Match All - Fatal编程技术网

Php 提取字符串上的每个匹配项

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]);

我有一个字符串,格式是“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]);
}
输出:

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)
从第二个字符转换为倒数第二个字符。谢谢大家!非常好的输入!