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

时间:2012-10-25 12:37:07

标签: php regex replace tags

我有类似<code> <1> <2> </code>的内容,我希望得到这个:<code> &lt;1&gt; &lt;2&gt; </code>但我想仅在<code></code>代码中应用此内容,而不是在其他任何地方。

我已经有了这个:

$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></code>标记

任何帮助将非常感谢!感谢

2 个答案:

答案 0 :(得分:2)

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

<?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>";
}

在没有第二功能的情况下实现这一点并不容易(不确定是否可能),因为可能存在多个&lt;块内的符号。

在这里阅读更多内容: http://php.net/preg_replace_callback

答案 1 :(得分:0)

你可以使用正则表达式,但不能一次性完成。我建议你单独处理你的其他替换品。下面的代码将处理&lt; code&gt;中的伪代码。部分:

$source = '<code> <1> <2> </code>';

if ( preg_match_all( '%<code>(.*?<.*?)</code>%s', $source, $code_sections ) ) {

    $modified_code_sections = preg_replace( '/<([^<]+)>/', "&lt;$1&gt;", $code_sections[1] );
    array_walk( $modified_code_sections, function ( &$content ) { $content = "<code>$content</code>"; } );
    $source_modified = str_replace( $code_sections[0], $modified_code_sections, $source );

}

echo $source_modified;