Re: preg_replace does not replace all occurrences

From: Date: Tue, 15 Mar 2011 12:45:55 +0000
Subject: Re: preg_replace does not replace all occurrences
References: 1 2 3 4 5  Groups: php.internals 
Request: Send a blank email to internals+get-51698@lists.php.net to get a copy of this message
Now, here is a pattern which actually means "a quote which doesn't already have a backslash before it" which is achieved by means of a lookbehind assertion, which, even when searching the string after the first match, "'str", still 'looks back' on the earlier part of the string to recognise the second quote is not preceded by a backslash and match a second time: /(^|(?<!\\))'/ As a PHP single-quoted string this is: '/(^|(?<!\\\\))\'/'
And I should mention, as Martin did, that this actually isn't a good idea. There are better/safer ways to escape quotes. In particular, consider how this subject string str\\'; delete from users; will not have the quote escaped, because it is preceded by *two* backslashes. To match more carefully, you have to be careful to 'eat backslashes in pairs'. Someone gave a pattern that attempted to do something like that in an earlier post, too. Ben.

« previous php.internals (#51698) next »