简体   繁体   English

PHP strip_tags(某些字符除外)

[英]PHP strip_tags except certain characters

I am using strip_tags in PHP to remove HTML tags when echoing data. 我在PHP中使用strip_tags在回显数据时删除HTML标签。

My string looks like: 我的字符串看起来像:

<br>
<br>
<br>
<br>
<br>
Test 1, Test2<br>
Test 3,<br>
<br>
<br>
<br>
<br>
<br>
Test 4<br>
Test 5<br>
<br>
Test 6 test 7

How can I remove the <br> tags that leave big gaps but keep the <br> tags between line gaps (like that between Test 1, Test2<br>Test3 )? 如何删除留有较大间隙的<br>标记,但将<br>标记保留在行间隙之间(如Test 1, Test2<br>Test3之间的标记)?

And just remove the: 只需删除:

<br>
<br>
<br>
<br>
<br>

So the string will end up looking like: 因此,字符串最终看起来像:

Test 1, Test2<br>
Test 3,<br>
Test 4<br>
Test 5<br>
<br>
Test 6 test 7

It's probably cleaner to do this in two steps: 分两步执行此操作可能更干净:

// remove <br> tags
$text = preg_replace('#^(<br[\\s]*(>|\/>)\s*){2,}$#im', '', $text);

// remove empty lines - from http://stackoverflow.com/a/709684/
$text = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", PHP_EOL, $text);

Explanation - #^(<br\\s*(>|\\/>)\\s*){2,}$#im 说明- #^(<br\\s*(>|\\/>)\\s*){2,}$#im

  • ^ - beginning of the line anchor ^ -行首锚
  • ( - first capturing group ( -第一个捕获组
    • <br - literal characters < , followed by b , followed by r <br文字字符< ,后跟b ,后跟r
    • \\s* - any whitespace character, zero or more times \\s* -任何空白字符,零次或多次
    • (>|\\/>) - alternation - match both <br> and <br/> (>|\\/>) -交替-匹配<br><br/>
    • \\s* - followed by optional whitespace \\s* -后跟可选的空格
  • ) - end of first capturing group ) -第一个捕获组的结尾
  • {2,} - match the previous group, 2 or more times {2,} -匹配上一组,两次或更多次
  • i - match both cases i -两种情况都匹配
  • m - make the pattern match lines separately m使图案分别与线条匹配

Output: 输出:

Test 1, Test2<br>
Test 3,<br>Test 4<br>
Test 5<br>
<br>
Test 6 test 7

Demo 演示

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

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