I want to change /<?phps([sS]*?)?>/gi the way that single line PHP tags become excluded. For example, here I want to match only second PHP tag and not the first one: Answer You can use A variation with multiline .: See the regex demo. Details: <?php – a <?php substring (?!S) – a right-hand whitespace boundary (immediately to the right, there