2013-12-12 21:19
浏览 111


This question is basically the same as How to extract the string in the quotes (either double quotes or single quotes), except in PHP.

Basically, I want a function like this:

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

However, this is not allowed in PHP: PHP Warning: preg_match_all(): Compilation failed: two named subpatterns have the same name.

My current solution seems overly complicated for a simple goal:

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

图片转代码服务由CSDN问答提供 功能建议



  function extract_tokens($ text){
 preg_match_all('/ Foo \((?:\'(?&lt; text&gt;。*?)\'|“(?&lt;  ; text&gt;。*?)“)\)/',$ text,$ matches); 
返回$ matches ['text']; 
 但是,这在PHP中是不允许的: PHP警告:preg_match_all():编译失败:两个命名的子模式具有相同的名称 

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

  function extract_tokens($ text){
 preg_match_all('/ Foo \((\'(。*?)\'|“  (。*?)“)\)/',$ text,$ matches); 
返回array_map(函数($ token){
返回substr($ token,1,strlen($ token) -  2); \  n},$ matches [1]); 
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doufei2355 2013-12-12 21:22

    You can try this:

    function extract_tokens($text) {
        preg_match_all('/Foo\(([\'"])(?<text>.*?)\1\)/', $text, $matches);
        return $matches['text'];
    解决 无用
    打赏 举报

相关推荐 更多相似问题