【问题标题】:How to replace new lines by regular expressions如何用正则表达式替换新行
【发布时间】:2011-04-01 23:54:27
【问题描述】:

如何使用正则表达式设置任意数量的新行?

$var = "<p>some text</p><p>another text</p><p>more text</p>";
$search = array("</p>\s<p>");
$replace = array("</p><p>");
$var = str_replace($search, $replace, $var);

我需要删除两个段落之间的每一行 (\n),而不是 &lt;br/&gt;

【问题讨论】:

  • 你的意思是在两个段落之间的每一个新行吗?看起来您搜索的“结束段落,内容,开始段落”被“结束 p,开始 p”取代 ---- 另外,$var 是否应该在您的示例中有任何匹配项?
  • $var 在您的示例中不包含任何新行。
  • 你想如何处理 &lt;p&gt; 元素内的元素,例如带有换行符的span

标签: php regex replace


【解决方案1】:

我觉得有巨大的 HTML 字符串很奇怪,然后使用一些字符串搜索和替换 hack 来格式化...

在使用 PHP 构建 HTML 时,我喜欢使用数组:

$htmlArr = array();
foreach ($dataSet as $index => $data) {
   $htmlArr[] = '<p>Line#'.$index.' : <span>' . $data . '</span></p>';
}

$html = implode("\n", $htmlArr);

这样,每个 HTML 行都有其单独的 $htmlArr[] 值。此外,如果您需要您的 HTML 是“漂亮的打印”,您可以简单地使用某种方法来缩进您的 HTML,方法是根据某些规则集在每个数组元素的开头添加空格。例如,如果我们有:

$htmlArr = array(
  '<ol>',
  '<li>Item 1</li>',
  '<li><a href="#">Item 2</a></li>',
  '<li>Item 3</li>',
  '</ol>'
);

那么格式化函数算法将是(一个非常简单的算法,考虑到 HTML 构造良好):

$indent = 0; // Initial indent
foreach & $value in $array
   $open = Count how many opened elements
   $closed = Count how many closed elements
   $value = str_repeat(' ', $indent * TAB_SPACE) . $value;
   $indent += $open - $closed;  // Next line's indent
end foreach

return $array

然后implode("\n", $array) 用于漂亮的 HTML

Felix Kling 编辑问题后,我意识到这与问题无关。对此感到抱歉:)感谢您的澄清。

【讨论】:

    【解决方案2】:

    首先,str_replace()(您在原始问题中引用)用于查找文字字符串并替换它。 preg_replace() 用于查找与正则表达式匹配的内容并将其替换。

    在下面的代码示例中,我使用\s+ 来查找一个或多个空格(新行、制表符、空格...)。 \s is whitespace,而+ 修饰符表示前面的一个或多个。

    <?php
      // Test string with white space and line breaks between paragraphs
    $var = "<p>some text</p>    <p>another text</p>
    <p>more text</p>";
    
      // Regex - Use ! as end holders, so that you don't have to escape the
      // forward slash in '</p>'. This regex looks for an end P then one or more (+)
      // whitespaces, then a begin P. i refers to case insensitive search.
    $search = '!</p>\s+<p>!i';
    
      // We replace the matched regex with an end P followed by a begin P w no
      // whitespace in between.
    $replace = '</p><p>';
    
      // echo to test or use '=' to store the results in a variable. 
      // preg_replace returns a string in this case.
    echo preg_replace($search, $replace, $var);
    ?>
    

    Live Example

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-12
      • 1970-01-01
      • 2019-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多