我有类似 的东西<1><2></code> 我想得到这个:<1><2></code> 但我只想在 <code></code> 标签内应用它,而不是在其他任何地方.
I have something like <code> <1> <2> </code> and I would like to get this : <code> <1> <2> </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", "<" ); $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('<' => '<','>' => '>'); $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> 之间的特定字符和</tag>在 PHP 中
发布评论