【问题标题】:extract every occurrence on string提取字符串上的每次出现
【发布时间】:2011-02-15 13:17:23
【问题描述】:

我有一个"a-b""c-d""e-f"... 形式的字符串 使用preg_match,我如何提取它们并得到一个数组:

Array
(
    [0] =>a-b
    [1] =>c-d
    [2] =>e-f
    ...
    [n-times] =>xx-zz
)

谢谢

【问题讨论】:

  • 谢谢大家!很好的意见!

标签: php regex preg-match preg-match-all


【解决方案1】:

正则表达式并不总是最快的解决方案:

$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 ) 从第二个字符到倒数第二个字符。
【解决方案2】:

这是我的看法。

$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_match_all() 在索引 1-9 中返回每个捕获的组,而整个模式匹配在索引 0 处。因为我们只想要捕获中的内容组(在本例中为第一个捕获组),我们查看$matches[1]

【讨论】:

    【解决方案3】:

    你可以这样做:

    $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"
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-20
      • 2021-04-19
      • 1970-01-01
      • 2016-07-25
      • 2020-11-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多