【问题标题】:RegEx for preg_match_all not workingpreg_match_all 的正则表达式不起作用
【发布时间】:2013-05-09 11:53:02
【问题描述】:

这是我的字符串 ($string):

    swatch: 'http://abc.com/aa.jpg',
    zoom:[
      'http://abc.com/bb.jpg'
    ],
    large:[

      'http://abc.com/cc.jpg'
    ],

我在我的 PHP 文件中使用以下模式并希望匹配 http://abc.com/bb.jpg:

preg_match_all('/(?<=zoom:\[\s{15}\').*(?=\')/', $string, $image);

但没有返回任何内容。我应该怎么办?

【问题讨论】:

  • 搞笑,你真的数过空格数吗?使用 \s* 并添加 s 修饰符以匹配新行 :) 如果这是 JSON,请改用 json_decode()
  • 哎呀,你不能在 PHP 的环视中使用量词...
  • 据我所知,您不能在任何环视引擎中使用量词。我同意为此使用json_decode() 而不是正则表达式。

标签: php regex preg-match-all


【解决方案1】:

为了更简单,我们不会使用环视,虽然我说我们需要 s 修饰符,但我错了,它只用于匹配带有点 . 的新行,我们不会使用在这里,\s 匹配一个新行:

$string = <<<JSO
        swatch: 'http://abc.com/aa.jpg',
        zoom:[
          'http://abc.com/bb.jpg'
        ],
        large:[

          'http://abc.com/cc.jpg'
        ],
JSO;
preg_match_all('/zoom:\[\s*\'(?<img>[^\']*)\'\s*\]/', $string, $m);
print_r($m['img']);

输出:

Array
(
    [0] => http://abc.com/bb.jpg
)

说明:

/ # Starting delimiter
    zoom:\[ # Matches zoom:[
    \s* # Matches spaces, newlines, tabs 0 or more times
    \'  # Matches '
    (?<img>[^\']*) # named group, matches everything until ' found
    \'  # Matches '
    \s* # Matches spaces, newlines, tabs 0 or more times
    \]  # Matches ]
/ # Ending delimiter

【讨论】:

  • 谢谢。结尾的's'是什么意思?
  • @user1610115 你的意思是\s* 吗?这将匹配空格、换行符、制表符 0 次或更多次。否则有 s 修饰符,用于将换行符与点 . 匹配。
猜你喜欢
  • 1970-01-01
  • 2013-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-23
相关资源
最近更新 更多