Jump to content

[SOLVED] Extractine quoted string from a string


Mark Baker

Recommended Posts

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 />';

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.