PHP:带状包裹段落标签
我需要编写一个 PHP 函数,该函数从字符串中删除开始和结束段落标记,但前提是它们位于最开头/结尾。所以字符串:
"Simple Test"
"<p>Here</p>"
"<p>Test <p>Nested</p> Outside </p>"
输出:
"Simple Test"
"Here"
"Test <p>Nested</p> Outside"
HTMLPurifier 可以做到这一点还是我应该使用 substr?我的第一次尝试是:
if(strpos($str,'<p>') === 0 && strcmp(substr($str,-1,4),'</p>'))
$str = substr($str,3,strlen($str)-4);
I need to write a PHP function which removes opening and closing paragraph tags from a string, but only if they are at the very beginning/end. So the strings:
"Simple Test"
"<p>Here</p>"
"<p>Test <p>Nested</p> Outside </p>"
Would Output:
"Simple Test"
"Here"
"Test <p>Nested</p> Outside"
Can HTMLPurifier do this or should I use substr? My first attempt was:
if(strpos($str,'<p>') === 0 && strcmp(substr($str,-1,4),'</p>'))
$str = substr($str,3,strlen($str)-4);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是一个正则表达式解决方案:
This is a regex solution:
这是正则表达式的方式。
如果唯一的要求是去掉精确的包装字符串
和
如果你需要一个对 html 来说是健壮的通用解决方案,那么你应该使用 DOM。
(例如,如果您想在换行段落标签中接受类、ID 和各种属性。)
但请注意,加载 domdocument 将使您的 html 标准化。
这将生成以下输出:
您可以轻松地制作一个衬垫。例如,使用 preg_replace 和正则表达式反向引用,您可以替换匹配的字符串...但我希望这种形式对您来说更容易理解。
this is a regex way.
its fine if the only requirement is to strip the exact wrapping strings
<p>
and</p>
if you need a generic solution which is robust for html you should use DOM.
(for example if you want to acceppt classes, ids and variaous attributes in your wrapping paragraph tags.)
but be aware that loading a domdocument will normalize your html.
this will generate this output:
you could easily make thie a one liner. for example with preg_replace and regex backreferences you could replace the string which the match... but i hope in this form its more understandable to you.
像这样的正则表达式
将匹配您的
,
和
- 使用该正则表达式并将匹配项替换为空字符串或任何您喜欢的内容。
HTH
PS:使用“忽略大小写”标志,以防万一。
编辑:使该组成为非捕获组。
A Regular Expression like
will match your <p\ >, </p> and <p somestuff> - use that regexp and replace matches with emtpy string or whatever you like.
HTH
PS: use the "ignore case" flag, just in case.
Edit: made the group a non-capturing one.
不太花哨的模式,但有效
$inf = preg_replace('/<[\/]*?p.*?>/', '', $info);
The not so fancy pattern, but works
$inf = preg_replace('/<[\/]*?p.*?>/', '', $info);