preg_match 第二个斜杠后向后看
preg_match lookbehind after second slash
这是我的字符串:
stringa/stringb/123456789,abc,cde
和 preg_match 之后:
preg_match('/(?<=\/).*?(?=,)/',$array,$matches);
输出为:
stringb/123456789
如何更改 preg_match 以在第二个斜线(或最后一个斜线之后)后提取字符串?
期望的输出:
123456789
您可以将 /
以外的任何内容匹配为
/(?<=\/)[^\/,]*(?=,)/
[^\/,]*
否定字符 class 匹配 ,
或 \
以外的任何字符
例子
preg_match('/(?<=\/)[^\/,]*(?=,)/',$array,$matches);
// $matches[0]
// => 123456789
应该这样做。
<?php
$array = 'stringa/stringb/123456789,abc,cde';
preg_match('~.*/(.*?),~',$array,$matches);
echo $matches[1];
?>
忽略最后一个正斜杠 (.*/
) 之前的所有内容。找到最后一个正斜杠后,保留所有数据,直到第一个逗号 ((.*?),
).
您不需要使用 lookbehind,即:
$string = "stringa/stringb/123456789,abc,cde";
$string = preg_replace('%.*/(.*?),.*%', '', $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) «*»
Insert the text that was last matched by capturing group number 1 «»
这是我的字符串:
stringa/stringb/123456789,abc,cde
和 preg_match 之后:
preg_match('/(?<=\/).*?(?=,)/',$array,$matches);
输出为:
stringb/123456789
如何更改 preg_match 以在第二个斜线(或最后一个斜线之后)后提取字符串?
期望的输出:
123456789
您可以将 /
以外的任何内容匹配为
/(?<=\/)[^\/,]*(?=,)/
[^\/,]*
否定字符 class 匹配,
或\
以外的任何字符
例子
preg_match('/(?<=\/)[^\/,]*(?=,)/',$array,$matches);
// $matches[0]
// => 123456789
应该这样做。
<?php
$array = 'stringa/stringb/123456789,abc,cde';
preg_match('~.*/(.*?),~',$array,$matches);
echo $matches[1];
?>
忽略最后一个正斜杠 (.*/
) 之前的所有内容。找到最后一个正斜杠后,保留所有数据,直到第一个逗号 ((.*?),
).
您不需要使用 lookbehind,即:
$string = "stringa/stringb/123456789,abc,cde";
$string = preg_replace('%.*/(.*?),.*%', '', $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) «*»
Insert the text that was last matched by capturing group number 1 «»