【问题标题】:Replace newlines with br but ignore newlines after h1 in PHP用 br 替换换行符,但在 PHP 中忽略 h1 之后的换行符
【发布时间】:2010-02-23 19:12:42
【问题描述】:

是否可以用<br> 标签替换换行符,但忽略</h1> 标签后面的换行符?

所以例如我想改变这个块:

<h1>Test</h1> \n some test here \n and here

到这里:

<h1>Test</h1> some test here <br /> and here

【问题讨论】:

  • 一开始为什么会有这样的代码?看来你原来的情况本身就有问题。

标签: php newline


【解决方案1】:
$subject = "<h1>hithere</h1>\nbut this other\nnewline should be replaced.";
$new = preg_replace("/(?<!h1\>)\n/","<br/>",$subject);
echo $new;

// results in:
// <h1>hithere</h1>
// but this other<br/>newline should be replaced.

应该可以。这表示 \n 之前没有立即被 h1>

【讨论】:

    【解决方案2】:

    使用字符串函数而不是正则表达式,并假设&lt;/h1&gt; 标记可以位于行中的任何位置(而不是就在换行符之前):

    $lines=file($fn);
    foreach ($lines as $line) {
      if (stristr("$line", "</h1>") == FALSE) {
        $line = str_replace("\n", "<br />", $line);
      }
      echo $line;
    }
    

    对于您的示例,结果如下:

    &lt;h1&gt;Test&lt;/h1&gt;
    一些测试在这里&lt;br /&gt;和这里&lt;br /&gt;

    【讨论】:

      猜你喜欢
      • 2011-11-14
      • 2020-08-08
      • 1970-01-01
      • 2022-08-07
      • 2016-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多