【问题标题】:Extract single and double quoted strings提取单引号和双引号字符串
【发布时间】:2013-12-12 21:19:57
【问题描述】:

这个问题和How to extract the string in the quotes (either double quotes or single quotes)基本一样,除了PHP。

基本上,我想要一个这样的函数:

function extract_tokens($text) {
    preg_match_all('/Foo\((?:\'(?<text>.*?)\'|"(?<text>.*?)")\)/', $text, $matches);
    return $matches['text'];
}

但是,这在 PHP 中是不允许的:PHP Warning: preg_match_all(): Compilation failed: two named subpatterns have the same name

对于一个简单的目标,我目前的解决方案似乎过于复杂:

function extract_tokens($text) {
    preg_match_all('/Foo\((\'(.*?)\'|"(.*?)")\)/', $text, $matches);
    return array_map(function($token) {
        return substr($token, 1, strlen($token) - 2);
    }, $matches[1]);
}

【问题讨论】:

    标签: php regex


    【解决方案1】:

    你可以试试这个:

    function extract_tokens($text) {
        preg_match_all('/Foo\(([\'"])(?<text>.*?)\1\)/', $text, $matches);
        return $matches['text'];
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-09
      • 2015-10-29
      • 2012-07-07
      • 2017-02-26
      • 1970-01-01
      • 2011-04-12
      • 1970-01-01
      相关资源
      最近更新 更多