将“//” - 带前缀的文本替换为空格(如果不在引号内)

时间:2012-08-04 22:58:56

标签: php

匹配数组行中的//,如果//不在" "内,则将//this is a test "this is a // test" 替换为空格。 例如,我有这一行:

//

输出应为:


"this is a // test"

它会忽略""

中的$string[$i] = preg_replace('#(?<!")//.*(?!")#',' ',$string[$i]);

现在我想出了这个正则表达式:

//

但如果{{1}}位于一行的中间或最后一部分,则不起作用。

2 个答案:

答案 0 :(得分:1)

由于您不必担心跨越多行的报价,这使您的工作变得更加容易。

一种方法是使用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;

我们得到以下输出:


"this is a // test"
"Find me some horsemen!" 
"I am walking toward a bright light." "This is a // test" 

答案 1 :(得分:1)

我不了解RegEx,但您可以使用substr_replacestrpos轻松实现此目的:

$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"