[英]how to regex character < and > replace like < and > in tag <code> </code>?
我有一个像bellow的字符串:
<pre title="language-markup">
<code>
<div title="item_content item_view_content" itemprop="articleBody">
abc
</div>
</code>
</pre>
在<code></code>
标记中,我想用<
替换所有字符<
和>
<
和>
。 我应该怎么做?
示例: <code> < div ><code>
<code> < div ><code>
。
如果您有任何想法,请告诉我。 谢谢大家。
别。 使用htmlspecialchars 。 那只是为了达到这个目的
echo htmlspecialchars("<a href='test'>Test</a>");
输出您的HTML代码
<pre title="language-markup"><code>
<div title="item_content item_view_content"
itemprop="articleBody">abc</div></code></pre>
另一个基于您的评论的例子
<code>
<?php
echo htmlspecialchars('html here');?>
</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>
<div title="item_content item_view_content" itemprop="articleBody">
abc
</div>
</code>
</pre>
使用htmlspecialchars()
或htmlentities()
$string = "<html></html>"
// Do this
$encodedString = htmlentities($string);
// or
$encodedString = htmlspecialchars($string);
这两个函数的不同之处在于,将编码所有内容或更好地表示“实体”。 另一个只会编码特殊字符。
以下是PHP.net的一些引用
此函数在所有方面与htmlspecialchars()相同,除了htmlentities()之外,所有具有HTML字符实体等效项的字符都将转换为这些实体。
某些字符在HTML中具有特殊意义,如果要保留其含义,则应由HTML实体表示。 此函数返回一个字符串,其中包含一些转换; 所做的翻译是对日常网络编程最有用的翻译。 如果要翻译所有HTML字符实体,请改用htmlentities()。
好的,我正在努力解决我的问题。 我成功了,这是我解决问题的代码。 您可以使用我的方式或使用Chetan Ameta的方式来回答我:
function replaceString($string)
{
preg_match_all('/<code>(.*?)<\/code>/', $string, $matches);
$result = [];
foreach ($matches[1] as $key => $match) {
$result[$key] = str_replace(['<', '>'], ['<', '>'], $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);
我喜欢这个地方,谢谢大家的帮助,我很感激。 再次感谢。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.