簡體   English   中英

如何用正則表達式替換新行

[英]How to replace new lines by regular expressions

如何使用正則表達式設置任意數量的新行?

$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 ),而不是<br/>

首先,str_replace() (您在原始問題中引用了它)用於查找文字字符串並替換它。 preg_replace()用於查找與正則表達式匹配的內容並替換它。

在以下代碼示例中,我使用\\s+查找一個或多個空格(換行、制表符、空格...)。 \\s是空格+修飾符表示前面的一個或多個。

<?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);
?>

現場示例

我發現擁有巨大的 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

然后對漂亮的 HTML 內implode("\\n", $array)

在 Felix Kling 編輯問題后,我意識到這與問題無關。 對此很抱歉:) 謝謝你的澄清。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM