【问题标题】:Php preg_match to capture only specific phrasesphp preg_match 仅捕获特定短语
【发布时间】:2014-03-11 09:52:54
【问题描述】:

示例字符串:

$string = 'text text text text {capture this1, this2} text text text text';

我想使用preg_match,仅将这些this1this2 放在一个数组中,仅此而已。

我正在尝试这样的事情:

$array = array();
$reg = '/\{capture.*\}/'; //this needs changing
preg_match($reg, $string, $array);
var_dump($array);

这会捕获{capture this1, this2}。如何从正则表达式中排除“{”符号?我正在尝试类似.!\{ 的东西,但它给了我错误。有什么建议吗?

【问题讨论】:

  • 所以你只需要capture this1, this2 ?
  • 不,我需要this1this2,数组看起来像array('this1', 'this2')
  • 用一个表达式来做{capture\s*\K[^,{}]+(?=[^}]*})|\G(?<!^),\s*\K[^,{}]+(?=[^}]*}),解释起来很痛苦。见demo :)
  • 谢谢 HamZa,好像它返回了我需要的东西,我现在将检查它:) 谢谢
  • @HamZa 你是巫师吗?

标签: php regex


【解决方案1】:

您可以尝试以下正则表达式:

/\{(capture[^}]*)\}/

【讨论】:

    【解决方案2】:

    你可以用这个:

    $pattern = '~(?:{capture |\G(?!\A), )\K[^,}]+(?=(})?)~';
    $data = 'text text text {capture this1, this2} text text';
    $tmp = array();
    
    if (preg_match_all($pattern, $data, $matches, PREG_SET_ORDER)) {
        foreach($matches as $m) {
            $tmp[] = $m[0];
            if (isset($m[1])) {
                $result = $tmp;
                break; 
            }
        }
    }
    print_r($result);
    

    此模式避免使用此前瞻 (?=[^}]*}) 来检查右大括号是否存在,并使用更快测试的 (?=(})?)。如果捕获组存在,就知道括号是闭合的。

    但是我认为 Shankar Damodaran 方法更简单(并且可能更有效)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-26
      • 1970-01-01
      • 2011-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多