Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use php preg_replace to replace HTML tags

Tags:

regex

php

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

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

like image 351
Juanjo Conti Avatar asked Jul 30 '10 23:07

Juanjo Conti


People also ask

How to avoid HTML tags in PHP?

PHP provides an inbuilt function to remove the HTML tags from the data. The strip_tags() function is an inbuilt function in PHP that removes the strings form HTML, XML and PHP tags. It accepts two parameters. This function returns a string with all NULL bytes, HTML, and PHP tags stripped from a given $str.

How to remove HTML tags from text in PHP?

The strip_tags() function strips a string from HTML, XML, and PHP tags. Note: HTML comments are always stripped. This cannot be changed with the allow parameter. Note: This function is binary-safe.


3 Answers

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.

like image 64
NullUserException Avatar answered Sep 27 '22 20:09

NullUserException


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);
like image 25
JAL Avatar answered Sep 27 '22 18:09

JAL


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!

like image 35
Amit Verma Avatar answered Sep 27 '22 20:09

Amit Verma