正则表达式替换<p>和</p>之间的

时间:2017-07-31 08:44:58

标签: php regex

我有一串html,其中包含许多<p>标记和其他html标记。

如何在<br /><p>标记之间替换</p>代码,以便它使用正则表达式成为多个段落?

(我只需要替换<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>

2 个答案:

答案 0 :(得分:2)

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

sandbox code

答案 1 :(得分:-1)

使用PHP函数str_replace。它将取代所有“br”标签。像这样使用它:

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