【问题标题】:Replace specific character only between <tag> and </tag> in PHP仅在 PHP 中的 <tag> 和 </tag> 之间替换特定字符
【发布时间】:2012-10-15 15:30:58
【问题描述】:

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

我已经有了这个:

$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);

它成功替换了字符但它删除了包围的&lt;code&gt;&lt;/code&gt;标签

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

【问题讨论】:

标签: php regex replace tags


【解决方案1】:

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

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

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

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

【讨论】:

  • 我需要做一些类似的事情(在标签中替换所有 : 和 = 直到我的笑脸运行)所以我修改了这段代码,它工作得非常好!为什么你没有起床投票更多地击败了我。感谢您的精彩回答!
【解决方案2】:

您可以使用正则表达式来完成,但不能一次性完成。我建议您单独处理其他替代品。下面的代码将处理 部分中的伪标签:

$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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-21
    • 2016-09-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多