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

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.