1

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;" 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.

Thanks.

1 Answer 1

1

You can use this regex with s switch (DOTALL) for search:

'/use [^\n]*(?!.*?use)/s'

Online Demo: http://regex101.com/r/dX9hQ9

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);

Explanation:

  • s modifier makes dot match new lines
  • use [^\n]* matches text use untile new line is found
  • (?!.*?use) is a Negative Lookahead which matches previous regex only if it is not followed by another use
Sign up to request clarification or add additional context in comments.

3 Comments

can you explain it a bit more.. i will very apreciate it. btw thanks for the answer :) .
ahhh okay... i see the bottom of your link.. there is explanation there.. thanks ;)
Yes I added but regex101 has quite a detailed explanation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.