preg_match查找第二个斜杠后面的内容

4
这是我的字符串:
stringa/stringb/123456789,abc,cde

并且在 preg_match 之后:

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

输出结果为:

stringb/123456789

我该如何修改preg_match函数来提取第二个斜杠(或最后一个斜杠)后面的字符串?
期望的结果是:
123456789
3个回答

4

您可以匹配除/以外的任何内容。

/(?<=\/)[^\/,]*(?=,)/
  • [^\/,]* 表示匹配除了 , 或者 \ 以外的任何字符

正则表达式演示

示例

preg_match('/(?<=\/)[^\/,]*(?=,)/',$array,$matches);
// $matches[0]
// => 123456789

谢谢,它有效!难道不应该是[...]而不是,/吗? - Driver
@Driver 在正则表达式中,[^ ] 表示否定字符集。因此,如果要匹配除了逗号和斜杠之外的任何字符,应该使用 [^,\/] - nu11p01n73R

2
这应该可以解决问题。
<?php
$array = 'stringa/stringb/123456789,abc,cde';
preg_match('~.*/(.*?),~',$array,$matches);
echo $matches[1];
?>

忽略掉最后一个反斜杠(.*/)之前的所有内容。一旦找到最后一个反斜杠,保留所有数据直到第一个逗号出现((.*?),)。

0

你不需要使用回顾后发表达式,即:

$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»

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接