0

匹配//一行数组中的 a ,//如果它不在里面,则用空格替换" "。例如我有这一行:

//this is a test
"this is a // test"

输出应该是:

“这是一个测试”

它会忽略//里面""

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

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

//但如果它位于一行的中间或最后一部分,这将不起作用。

4

2 回答 2

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;

我们得到以下输出:

“这是一个测试”
“给我找几个骑兵!”
“我正朝着明亮的灯光走去。” “这是一个测试”
于 2012-08-04T23:42:43.867 回答
1

我不知道,但是您可以使用andRegEx轻松实现此目的: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"
于 2012-08-04T23:49:49.870 回答