Juanjo Conti
Juanjo Conti

Reputation: 30013

How to use php preg_replace to replace HTML tags

I'd like to change <pre> with <code> and </pre> with </code>.

I'm having problem with the slash / and regex.

Upvotes: 7

Views: 31705

Answers (3)

Amit Verma
Amit Verma

Reputation: 41209

I found a very easy solution to replace multiple words in a string :

<?php
 $str="<pre>Hello world!</pre>";


$pattern=array();
$pattern[0]="/<pre>/";
$pattern[1]="/<\/pre>/";


$replacement=array();
$replacement[0]="<code>";
$replacement[1]="</code>";

echo preg_replace($pattern,$replacement,$str);?> 

output :

 <code>Hello world!</code>

With this script you can replace as many words in a string as you want :

just place the word (that you want to replace) in the pattern array , eg :

     $pattern[0]="/replaceme/"; 

and place the characters (that will be used in place of the replaced characters) in the replacement array, eg :

      $replacement[0]="new_word"; 

Happy coding!

Upvotes: 1

NullUserException
NullUserException

Reputation: 85458

You could just use str_replace:

$str = str_replace(array('<pre>', '</pre>'), array('<code>', '</code>'), $str);

If you feel compelled to use regexp:

$str = preg_replace("~<(/)?pre>~", "<\\1code>", $str);

If you want to replace them separately:

$str = preg_replace("~<pre>~", '<code>', $str);
$str = preg_replace("~</pre>~", '</code>', $str);

You just need to escape that slash.

Upvotes: 18

JAL
JAL

Reputation: 21563

You probably need to escape the /s with \s, or use a different delimiter for the expression.

Instead, though, how about using str_replace? <pre> and </pre> will be easy to match as they're not likely to contain any classnames or other attributes.

$text=str_replace('<pre>','<code>',$text);
$text=str_replace('</pre>','</code>',$text);

Upvotes: 3

Related Questions