tags:

views:

51

answers:

3

I want to change

<lang class='brush:xhtml'>test</lang>

to

<pre class='brush:xhtml'>test</pre>

my code like that.

<?php
$content="&lt;lang class='brush:xhtml'&gt;test&lt;/lang&gt;";
$pattern=array();
$replace=array();
$pattern[0]="/&lt;lang class=([A-Za-z='\":])* &lt;/";
$replace[0]="<pre $1>";

$pattern[1]="/&lt;lang&gt;/";
$replace[1]="</pre>";
echo preg_replace($pattern, $replace,$content);
?>

but it's not working. How to change my code or something wrong in my code ?

+2  A: 

How bout without regex? :)

<?php
$content="&lt;lang class='brush:xhtml'&gt;test&lt;/lang&gt;";
$content = html_entity_decode($content);
$content = str_replace('lang','pre',$content);
echo $content;
?>
robertbasic
Of course, that's going to change tons of other stuff he didn't specify; `html_entity_decode` will change any html entity, not just `<` and `>`, and the `str_replace` will change any instance of `lang`, not just tags
Michael Mrozek
I can't because it contain some html code . Like that<lang class='brush:xhtml'><html></html></lang>So, I can't do like that.
saturngod
+4  A: 

There's quite a few problems:

  • Pattern 0 has the * outside the group, so the group only matches one character
  • Pattern 0 doesn't include the class= in the group, and the replacement doesn't have it either, so there won't be a class= in the replaced string
  • Pattern 0 has a space after the class, but there isn't one in the content string
  • Pattern 1 looks for lang instead of /lang

This will work:

$pattern[0]="/&lt;lang (class=[A-Za-z='\":]*) ?&gt;/";
$replace[0]="<pre $1>";

$pattern[1]="/&lt;\/lang&gt;/";
$replace[1]="</pre>";
Michael Mrozek
+1 for explaining why the original one isn't working :)
robertbasic
Keeping it all in a single string `/<lang...<\/lang>/` though is a better practice. It's `112.03%` faster than breaking it up into two arrays.
N. Lucas
+1  A: 

Using preg_replace is a lot faster than str_replace.

$str = preg_replace("/&lt;lang class=([A-Za-z'\":]+)&gt;(.*?)&lt;\/lang&gt;/", "<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

So preg_replace is 218.31% faster than the str_replace method mentioned above. Each tested 1000 times.

N. Lucas