Mark Baker Posted March 8, 2009 Share Posted March 8, 2009 I'm looking for a regular expression that will extract a string from a variable: beginning at the first character and demarked by double quotes at the beginning and end, except that double quotes may exist within the quoted string, where they are escaped by duplicating the double quote ("") The code below shows my current efforts, with some test data, and the expected result: function testString($string) { echo 'Test Value is '.$string.'<br />'; $ex = preg_match('/^(\".*([^\"]\"))/i', $string, $match); if ($ex) { print_r($match); echo '<br />'; } else { echo 'No match found<br />'; } } $testData = '"Hello"'; testString($testData); echo '<b>Expected: </b>"Hello"<br /><br />'; $testData = 'Hello"Goodbye"'; testString($testData); echo '<b>Expected: </b>No match found<br /><br />'; $testData = '"Hello'; testString($testData); echo '<b>Expected: </b>No match found<br /><br />'; $testData = '"Hello"Goodbye'; testString($testData); echo '<b>Expected: </b>"Hello"<br /><br />'; $testData = '"Hello","Goodbye"'; testString($testData); echo '<b>Expected: </b>"Hello"<br /><br />'; $testData = '"Hello""Goodbye"'; testString($testData); echo '<b>Expected: </b>"Hello""Goodbye"<br /><br />'; $testData = '"Hel""lo","Goodbye"'; testString($testData); echo '<b>Expected: </b>"Hel""lo"<br /><br />'; $testData = '"Hello","Good""bye"'; testString($testData); echo '<b>Expected: </b>"Hello"<br /><br />'; $testData = '"Hel""lo""Good""bye"'; testString($testData); echo '<b>Expected: </b>"Hel""lo""Good""bye"<br /><br />'; $testData = '"Hello"Goodbye"Hello"'; testString($testData); echo '<b>Expected: </b>"Hello"<br /><br />'; $testData = '"Hel""lo"Goodbye'; testString($testData); echo '<b>Expected: </b>"Hel""lo"<br /><br />'; $testData = '"Hel""lo"Goodbye"He""llo"'; testString($testData); echo '<b>Expected: </b>"Hel""lo"<br /><br />'; Quote Link to comment Share on other sites More sharing options...
.josh Posted March 9, 2009 Share Posted March 9, 2009 preg_match('~^"(?:[^"]|"")*"~',$string,$match); edited to add a ^ to the beginning of the pattern; didn't notice you wanted it to only match if its at the beginning. Quote Link to comment Share on other sites More sharing options...
Mark Baker Posted March 9, 2009 Author Share Posted March 9, 2009 Thanks Crayon Violent That's giving me exactly what I need with the test data I'm currently using. I'll test it in the wild with real data, but looks good. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.