Php 正则表达式替换<;br/>;介于<;p>;及</p>;
我有一个html字符串,由许多Php 正则表达式替换<;br/>;介于<;p>;及</p>;,php,regex,Php,Regex,我有一个html字符串,由许多标记和其他html标记组成 如何使用regex替换和标记之间的标记,使其成为多个段落 (我只需要在标记中替换,而不需要在其他标记中替换) 样本来源: <p> This is a paragraph without line break</p> <p> This is a paragraph with <br /> line <br /> break</p> 这是一段没有换行符的段落 这是一段有
标记和其他html标记组成
如何使用regex替换
和
标记之间的
标记,使其成为多个段落
(我只需要在
标记中替换,而不需要在其他标记中替换)
样本来源:
<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函数str\u replace。它将替换所有“br”标记。像这样使用它:
$result = str_replace('<br />', '', $input);
$result=str_replace(“
”,“$input”);
您想用php编写regexp吗?或在任何其他语言中?建议使用代替preg_替换函数。或者您只需要替换
内部?从您的问题来看,如果
不在
标记之间,您似乎不想替换它-但是您的示例没有涵盖这一点。对不起,我只需要替换
内部,而不是其他标记中。忘了提到内部问题,“使用正则表达式”-为什么有这个要求。用这个。不要在html中使用正则表达式,它既不健康也不有趣。看这里。这不符合问题施加的“仅在p元素内部”限制。这不符合将换行符转换为问题强加的段落换行符的要求。它也是非常脆弱的,取决于br元素的非常具体的附录C形式。
<?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);