第二次斜线后preg_match lookbehind

时间:2015-05-04 15:50:04

标签: php regex preg-match

这是我的字符串:

stringa/stringb/123456789,abc,cde

并在preg_match之后:

preg_match('/(?<=\/).*?(?=,)/',$array,$matches);

输出是:

stringb/123456789

如何更改preg_match以在第二次斜杠后(或最后一次斜杠后)提取字符串?

期望的输出:

123456789

3 个答案:

答案 0 :(得分:4)

您可以将-Verbose:$false以外的任何内容匹配为

/
  • /(?<=\/)[^\/,]*(?=,)/ 否定字符类与[^\/,]*,
  • 以外的任何内容匹配

Regex Demo

示例

\

答案 1 :(得分:2)

这应该这样做。

<?php
$array = 'stringa/stringb/123456789,abc,cde';
preg_match('~.*/(.*?),~',$array,$matches);
echo $matches[1];
?>

忽略所有内容,直到最后一个正斜杠(.*/)。找到最后一个正斜杠后,将所有数据保留到第一个逗号((.*?),)。

答案 2 :(得分:0)

您不需要使用lookbehind,即:

$string = "stringa/stringb/123456789,abc,cde";
$string = preg_replace('%.*/(.*?),.*%', '$1', $string );
echo $string;
//123456789

演示:

http://ideone.com/IxdNbZ

正则表达式解释:

.*/(.*?),.*

Match any single character that is NOT a line break character «.*»
   Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
Match the character “/” literally «/»
Match the regex below and capture its match into backreference number 1 «(.*?)»
   Match any single character that is NOT a line break character «.*?»
      Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Match the character “,” literally «,»
Match any single character that is NOT a line break character «.*»
   Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»

$1

Insert the text that was last matched by capturing group number 1 «$1»