简体   繁体   English

PHP正则表达式删除前导和尾随 <br /> 内 <p> 标签

[英]PHP Regex Remove leading and trailing <br /> within <p> tags

I can't figure this out for the life of me. 我无法想象我的生活。

I need a regex expression that will strip out any leading or trailing <br> tags within <p> tags. 我需要一个正则表达式,它将删除<p>标记内的任何前导或尾随<br>标记。

For example. 例如。

<p> <br />Some test text. <br /> Some test text. Some test text. Some test text. Some test text. Some test text. Some test text. Some test text. Some test text. Some test text. Some test text. Some test text. <br /><br /><br /> </p>

Should become... 应该成为......

<p>Some test text. <br /> Some test text. Some test text. Some test text. Some test text. Some test text. Some test text. Some test text. Some test text. Some test text. Some test text. Some test text.</p>

I feel as though this should be very simple but I've hit a road-block. 我觉得这应该很简单,但我遇到了障碍。 Any help would be greatly appreciated. 任何帮助将不胜感激。

You just need a look-ahead and look-behind for <p> and </p> , and a non-capturing group for 1 or more occurrences of some variation of <br> . 你只需要一个前瞻和查找背后<p></p>以及1次或多次出现的一些变化的非捕获组<br>

For matching leading <br/> tags: 对于匹配主导<br/>标签:

(?<=<p>)(?:\s*<br\s*\/?>)+\s*

For matching trailing <br/> tags: 对于匹配尾随<br/>标签:

(?:\s*<br\s*\/?>)+\s*(?=<\/p>)

Both together: 两者一起:

(?<=<p>)(?:\s*<br\s*\/?>)+\s*|(?:\s*<br\s*\/?>)+\s*(?=<\/p>)

Regex101 Demo Regex101演示

We can do this without regular expressions. 我们可以在没有正则表达式的情

// Method1 :: Finding and replacing unwanted tags
$str1 = '<p> <br />Some test text. <br /> Some test text. Some test text. Some test text. Some test text. Some test text. Some test text. Some test text. Some test text. Some test text. Some test text. Some test text. <br /><br /><br /></p>';

$findTags = array('<br>', '<br />');
$replacement = array();

// Case insensitive replacement
$str1 = str_ireplace($findTags, $replacement, $str1);
print_r($str1);

// Method 2:: Stripping all HTML tags except allowed tags

$str2 = '<p> <br />Some test text. <br /> Some test text. Some test text. Some test text. Some test text. Some test text. Some test text. Some test text. Some test text. Some test text. Some test text. Some test text. <br /><br /><br /></p>';
$str2 = strip_tags($str2, '<p>');

echo $str2;
?>

Reference Links: 参考链接:

http://php.net/manual/en/function.str-replace.php http://php.net/manual/en/function.str-replace.php

http://php.net/manual/en/function.str-ireplace.php http://php.net/manual/en/function.str-ireplace.php

http://php.net/manual/en/function.strip-tags.php http://php.net/manual/en/function.strip-tags.php

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM