PHP正则表达式将html实体转换为各自的字符
我想换衣服PHP正则表达式将html实体转换为各自的字符,php,regex,Php,Regex,我想换衣服 <lang class='brush:xhtml'>test</lang> 到 我的代码就是这样 <?php $content="<lang class='brush:xhtml'>test</lang>"; $pattern=array(); $replace=array(); $pattern[0]="/<lang class=([A-Za-z='
<lang class='brush:xhtml'>test</lang>
到
我的代码就是这样
<?php
$content="<lang class='brush:xhtml'>test</lang>";
$pattern=array();
$replace=array();
$pattern[0]="/<lang class=([A-Za-z='\":])* </";
$replace[0]="<pre $1>";
$pattern[1]="/<lang>/";
$replace[1]="</pre>";
echo preg_replace($pattern, $replace,$content);
?>
但它不起作用。如何更改我的代码或代码中的某些错误?不使用正则表达式如何
<?php
$content="<lang class='brush:xhtml'>test</lang>";
$content = html_entity_decode($content);
$content = str_replace('lang','pre',$content);
echo $content;
?>
有很多问题: 模式0的*位于组外,因此组仅匹配一个字符 模式0在组中不包含class=,替换也没有,因此替换的字符串中不会有class= 模式0在类后有一个空格,但内容字符串中没有空格 模式1查找lang而不是/lang 这将有助于:
$pattern[0]="/<lang (class=[A-Za-z='\":]*) ?>/";
$replace[0]="<pre $1>";
$pattern[1]="/<\/lang>/";
$replace[1]="</pre>";
使用preg_replace比str_replace快得多
$str = preg_replace("/<lang class=([A-Za-z'\":]+)>(.*?)<\/lang>/", "<pre class=$1>$2</pre>", $str);
因此,preg_替换比上述str_替换方法快218.31%。每个人都测试了1000次。当然,这将改变他没有指定的其他很多东西;html_entity_decode将更改任何html实体,而不仅仅是and,str_replace将更改lang的任何实例,而不仅仅是tagsI无法更改,因为它包含一些html代码。就像lang class='brush:xhtml'>html/html/lang那样,我不能这样做。将所有内容保存在单个字符串中/lang…\/lang/虽然是一种更好的做法。它比将其拆分为两个阵列快112.03%。
$str = preg_replace("/<lang class=([A-Za-z'\":]+)>(.*?)<\/lang>/", "<pre class=$1>$2</pre>", $str);
Execution time: 0.039815s
[preg_replace]
Time: 0.009518s (23.9%)
[str_replace]
Time: 0.030297s (76.1%)
Test Comparison:
[preg_replace]
compared with.........str_replace 218.31% faster