这是我的字符串:
stringa/stringb/123456789,abc,cde
并在preg_match之后:
preg_match('/(?<=\/).*?(?=,)/',$array,$matches);
输出是:
stringb/123456789
如何更改preg_match以在第二次斜杠后(或最后一次斜杠后)提取字符串?
期望的输出:
123456789
答案 0 :(得分:4)
答案 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
演示:
正则表达式解释:
.*/(.*?),.*
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»