【发布时间】: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]);
}
【问题讨论】: