匹配一行数组中的//
,如果//
不在" "
内,则将其替换为空格。例如,我有这样一行:
//this is a test
"this is a // test"
输出应为:
"这是一个//测试">
它将忽略""
内部//
现在我想出了这个正则表达式:
$string[$i] = preg_replace('#(?<!")//.*(?!")#',' ',$string[$i]);
但是,如果//
位于行的中间或最后部分,则这不起作用。
由于您不必担心跨越多行的引号,这使您的工作变得更加轻松。
一种方法是逐行遍历输入并使用"
作为分隔符explode()
每一行:
$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;
使用以下测试字符串:
<?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;
我们得到以下输出:
"这是一个//测试"给我找几个骑兵!"我正走向明亮的光芒。"这是一个//测试">
我不知道
RegEx
但您可以使用substr_replace
和strpos
轻松实现:
$look = 'this is a "//" test or not //';
$output = "";
$pos = -1;
while($pos = strpos($look, '//'))
{
if(strpos($look, '"//') == ($pos - 1)) {
$output = $output.substr($look, 0, $pos + 4);
$look = substr($look, $pos + 4);
continue;
}
$output = $output .substr_replace(substr($look, 0, $pos + 2), '', $pos, 2);
$look = substr($look, $pos + 2);
}
//$output = "this is a // test or not"