php – Regex cant limit search range-ThrowExceptions

Exception or error:

I have following problem:

I have a pattern like this:


And an text like this:


My regex should search for the path infront of my file, i need to cut it out so that it will look at the end like this:


That works fine but the problem is that i have sometimes an text that looks like this:

block="core/template" template="test/widgets/getcallus.phtml"}}</p>

It cuts everything out till the </.

This is getting cutted out:


Instead of:


I have tried to limit the end with $ but it doesnt do nothing.

I am testing it on

How to solve:

You may use the following pattern:


See the regex demo. In PHP, you may get rid of backslashes if you specify another regex delimiter:

$regex = '~template="\K[^"/]*/[^"/]*/~';


  • template=" – literal text
  • \K – match reset operator
  • [^"\/]* – 0 or more chars other than / and "
  • \/ – a / char
  • [^"\/]* – 0 or more chars other than / and "
  • \/ – a / char

It is equal to template="\K(?:[^"\/]*\/){2}, where (?:...){2} repeats the non-capturing group sequence of patterns twice.


Be careful with (.*?)(.*\/)

This pattern corresponds to a REDOS vulnerability. (There are 2^n ways to read the n chars before the last /

To keep a regex closed to yours, you can use

([^"]*?\/)* reads as many blocks “non / nor " chars followed by /” as possible.

Leave a Reply

Your email address will not be published. Required fields are marked *