[英]Replace only the last matched string with preg replace php
I have this string : 我有这个字符串:
use A\B\C;
use A\B\C;
var $foo;
/*
* comment
*/
use D\E\F;
Class Foo {
How i can replace the last string that beginning with use. 我如何替换使用开始的最后一个字符串。 In example above must be "use D\\E\\F;" 在上面的示例中,必须为“ use D \\ E \\ F;”。 as the result. 作为结果。
I have found many ways but no luck. 我发现了很多方法,但是没有运气。 including with lookahead negative (?!) but was confused how to use it. 包括前瞻性负号(?!),但对如何使用它感到困惑。 So this the i can get now " use(.*); " but this was replaced all the matched string. 因此,我现在可以得到“ use(。*);”,但这已替换了所有匹配的字符串。
Thanks. 谢谢。
You can use this regex with s
switch (DOTALL) for search: 您可以将此正则表达式与s
开关(DOTALL)一起使用进行搜索:
'/use [^\n]*(?!.*?use)/s'
Code: 码:
$re = '/use [^\n]*(?!.*?use)/s';
$str = 'use A\B\C;
use A\B\C;
var $foo;
/*
* comment
*/
use D\E\F;
Class Foo {';
preg_match($re, $str, $matches);
s
modifier makes dot match new lines s
修饰符使点匹配新行 use [^\\n]*
matches text use
untile new line is found use [^\\n]*
匹配文本use
直到找到新行 (?!.*?use)
is a Negative Lookahead which matches previous regex only if it is not followed by another use
(?!.*?use)
是否定的超前行 ,仅当前一个正则表达式不跟随其他use
时才匹配
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.