仅替换 <tag> 之间的特定字符和&lt;/tag&gt;在 PHP 中

编程入门 行业动态 更新时间:2024-10-22 05:04:06
本文介绍了仅替换 <tag> 之间的特定字符和&lt;/tag&gt;在 PHP 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有类似 的东西<1><2></code> 我想得到这个:&lt;1>&lt;2></code> 但我只想在 <code></code> 标签内应用它,而不是在其他任何地方.

I have something like <code> <1> <2> </code> and I would like to get this : <code> &lt;1&gt; &lt;2&gt; </code> but I want to apply this only inside the <code></code> tags and not anywhere else.

我已经有了这个:

$txt = $this->input->post('field'); $patterns = array( "other stuff to find", "/<code>.*(<).*<\/code>/m" ); $replacements = array( "other stuff to replace", "&lt;" ); $records = preg_replace($patterns,$replacements, $txt);

它成功替换了字符,但它删除了包围的 </code> 标签

It replaces successfully the character but it removes the surrounded <code></code> tags

任何帮助将不胜感激!谢谢

Any help will be very appreciated ! Thanks

推荐答案

其他可能,使用回调函数:

Other possibility, using callback function:

<?php $test = "<code> <1> <2></code> some other text <code> other code <1> <2></code>"; $text = preg_replace_callback("#<code>(.*?)</code>#s",'replaceInCode',$test); echo htmlspecialchars($test."<br />".$text); function replaceInCode($row){ $replace = array('<' => '&lt','>' => '&gt'); $text=str_replace(array_keys($replace),array_values($replace),$row[1]); return "<code>$text</code>"; }

在没有第二个函数的情况下实现这一点并不容易(甚至不确定是否可能),因为可以有多个 <块内的符号.

It is not easy (not sure if even possible) to accomplish that without second function, as there can be multiple < symbols inside block.

在此处阅读更多信息:php/preg_replace_callback

更多推荐

仅替换 <tag> 之间的特定字符和&lt;/tag&gt;在 PHP 中

本文发布于:2023-11-01 18:20:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1550063.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符   tag   lt   gt   PHP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!