Re: Match anything between two " that is not a " except if it is escaped...

From: Date: Fri, 18 Jan 2008 14:36:00 +0000
Subject: Re: Match anything between two " that is not a " except if it is escaped...
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-267544@lists.php.net to get a copy of this message
A good habit is to use the hex equivalent character for any character that has a special meaning in pregex expressions. e.g., space = \x20 "/" = \x2f "." = \x2e double quotes = \x3d etc. Then you won't have this type of problem and you won't have to use stuff like this: This is for double quotes: '/"[^"\\\\]*(?:\\\\.[^"\\\\]*)*"/' this is for single: '/\'[^\'\\\\]*(?:\\\\.[^\'\\\\]*)*\'/' It's almost impossible to debug this nonsense. Also, use delimiters that do not occur in your pattern. I almost never use "/"; and instead like "%". I assume you know the delimiters can be almost any character. mathieu leddet wrote:
Hi everyone, I am struggling with regular expression trying to match strings delimited by double quotes, but taking into consideration that \" is not a string ending character. -------8<--------------------------------------------------------------- - $in = 'this is a string : "Hi everyone my name is \"Mathieu\"!" Here is a second string : "PHP is just perfect"'; // pattern for catching strings between " $pattern = '#"([^"]*)"#'; // surround matching string with HTML span code to highlight $replacement = '<b>"${1}"</b>'; // perform the reg exp replacement $out = preg_replace($pattern, $replacement, $in); -------8<--------------------------------------------------------------- - $out contains : this is a string : <b>"Hi everyone my name is \"</b>Mathieu\<b>"!"</b> Here is a second string : <b>"PHP is just perfect"</b> This behaviour is normal considering my pattern (anything between two " that is not a "). But I don't know how to get this : this is a string : <b>"Hi everyone my name is \"Mathieu\"!"</b> Here is a second string : <b>"PHP is just perfect"</b> I would like my pattern to express : Anything between two " that is not a " except if it is escaped. Thanks for reading me, any help in return is welcome ! -- Mathieu


« previous php.general (#267544) next »