如何正则化字符<;并且>;替换like&;lt;和&;gt;在标签<;代码></代码&g


how to regex character < and > replace like &lt; and &gt; in tag <code> </code>?

我有一个字符串,如下所示:

<pre title="language-markup">
    <code>
        <div title="item_content item_view_content" itemprop="articleBody">
            abc
        </div>
    </code>
</pre>

<code></code>标签中,我想用&lt;&gt;替换所有字符<>。我该怎么办?

示例:<code> &lt; div &gt;<code>

如果你有什么想法,请告诉我。谢谢大家。

尝试以下解决方案:

$textToScan = '<pre title="language-markup">
    <code>
        <div title="item_content item_view_content" itemprop="articleBody">
            abc
        </div>
    </code>
</pre>';

// the regex pattern (case insensitive & multiline
$search = "~<code>(.*?)</code>~is";
// first look for all CODE tags and their content
preg_match_all($search, $textToScan, $matches);
//print_r($matches);
// now replace all the CODE tags and their content with a htmlspecialchars() content
foreach($matches[1] as $match){
    $replace = htmlspecialchars($match);
    // now replace the previously found CODE block
    $textToScan = str_replace($match, $replace, $textToScan);
}
// output result
echo $textToScan;

输出:

<pre title="language-markup">
    <code>
        &lt;div title=&quot;item_content item_view_content&quot; itemprop=&quot;articleBody&quot;&gt;
            abc
        &lt;/div&gt;
    </code>
</pre>

不要。使用htmlspecialchars。这只是为了达到的目的

echo htmlspecialchars("<a href='test'>Test</a>");

HTML代码的输出

&lt;pre title=&quot;language-markup&quot;&gt;&lt;code&gt;
&lt;div title=&quot;item_content item_view_content&quot; 
itemprop=&quot;articleBody&quot;&gt;abc&lt;/div&gt;&lt;/code&gt;&lt;/pre&gt;

另一个基于你的评论的例子

<code>
<?php
echo htmlspecialchars('html here');?>
</code>

使用htmlspecialchars()htmlentities()

$string = "<html></html>"
// Do this
$encodedString = htmlentities($string);
// or
$encodedString = htmlspecialchars($string);

这两个函数的区别在于,一个函数将对所有内容或更好的"实体"进行编码。另一个只对特殊字符进行编码。

以下是PHP.net 的一些报价

从htmlentities的PHP文档中:

这个函数在所有方面都与htmlspecialchar()相同,除了使用htmlenties()之外,所有具有HTML字符实体等效项的字符都被翻译成这些实体。

从htmlspecialchars的PHP文档中:

某些字符在HTML中具有特殊意义,如果要保留其含义,则应使用HTML实体表示。此函数返回一个字符串,其中包含一些转换;所做的翻译对日常网络编程最有用。如果需要翻译所有HTML字符实体,请改用htmlenties()。

好的,我正在努力解决我的问题。我成功了,这是我解决问题的代码。你可以用我的方式,也可以用Chetan Ameta的方式来回答我的问题:

function replaceString($string)
{
    preg_match_all('/<code>(.*?)<'/code>/', $string, $matches);
    $result = [];
    foreach ($matches[1] as $key => $match) {
        $result[$key] = str_replace(['<', '>'], ['&lt;', '&gt;'], $match);
    }
    return str_replace($matches[1], $result, $string);
}
$string = '<pre title="language-markup"><code><div title="item_content item_view_content" itemprop="articleBody">abc</div></code></pre>';
echo replaceString($string);

我喜欢这个地方,谢谢大家帮助我,我非常感激。再次感谢。