仅替换 <tag> 之间的特定字符和&lt;/tag&gt;在 PHP 中 [英] Replace specific character only between &lt;tag&gt; and &lt;/tag&gt; in PHP

查看:39
本文介绍了仅替换 <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.

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

这篇关于仅替换 <tag> 之间的特定字符和&lt;/tag&gt;在 PHP 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆