Since you don't have to worry about quotes that span multiple lines, this makes your job significantly easier.
One approach would be to go through the input line-by-line and explode()
each line using "
as the delimiter:
$processed = '';
/* Split the input into an array with one (non-empty) line per element.
*
* Note that this also allows us to consolidate and normalize line endings
* in $processed.
*/
foreach( preg_split("/[\r\n]+/", $input) as $line )
{
$split = explode('"', $line);
/* Even-numbered indices inside $split are outside quotes. */
$count = count($split);
for( $i = 0; $i < $count; $i += 2 )
{
$pos = strpos($split[$i], '//');
if( $pos !== false )
{
/* We have detected '//' outside of quotes. Discard the rest of the line. */
if( $i > 0 )
{
/* If $i > 0, then we have some quoted text to put back. */
$processed .= implode('"', array_slice($split, 0, $i)) . '"';
}
/* Add all the text in the current token up until the '//'. */
$processed .= substr($split[$i], 0, $pos);
/* Go to the next line. */
$processed .= PHP_EOL;
continue 2;
}
}
/* If we get to this point, we detected no '//' sequences outside of quotes. */
$processed .= $line . PHP_EOL;
}
echo $processed;
Using the following test string:
<?php
$input = <<<END
//this is a test
"this is a // test"
"Find me some horsemen!" // said the king, or "king // jester" as I like to call him.
"I am walking toward a bright light." "This is a // test" // "Who are you?"
END;
We get the following output:
"this is a // test"
"Find me some horsemen!"
"I am walking toward a bright light." "This is a // test"