簡體   English   中英

正則表達式替換 <br /> 之間 <p> 和 </p>

[英]regex replace <br /> between <p> and </p>

我有一個包含許多<p>標記和其他html標記的html字符串。

如何在<p></p>標記之間替換<br />標記,以便使用正則表達式將其變為多個段落?

(我只需要替換<p>標記,而不是其他標記)

樣本來源:

<p> This is a paragraph without line break</p>
<p> This is a paragraph with <br /> line <br /> break</p>

樣本輸出:

<p> This is a paragraph without line break</p>
<p> This is a paragraph with </p><p> line </p><p> break</p>
<?php

$string = '<p> This is a paragraph without line break</p>
text <br /> without p <br />
<p> This is a paragraph with <br /> line <br /> break</p>
<p>aaaa <br /></p>
dsa<br />
<p><br /></p>';

// Start non-greedy search for text in paragraphs
preg_match_all('/<p>.*?<\/p>/im', $string, $matches);

$matches = $matches[0];

// for each match replace <br /> inside text
foreach ($matches as $key => $match) {
    $replaced[$key]['initial'] = $match;
    $replaced[$key]['replaced'] = str_replace('<br />', '</p><p>', $match);
}

// replacing initial parts of text with replaced parts
foreach ($replaced as $key => $replacePair) {
    $string = str_replace($replacePair['initial'], $replacePair['replaced'], $string);
}

print_r ($string);

沙盒代碼

使用PHP函數str_replace。 它將替換所有“ br”標簽。 像這樣使用它:

$result = str_replace('<br />', '', $input);

暫無
暫無

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

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