How to use php preg_replace to replace HTML tags

I would like to change <pre>to <code>and </pre>to </code>.

I have a problem with slash and regex.

+3
source share
3 answers

You can just use str_replace:

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

If you are forced 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 avoid this slash.

+12
source

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

, str_replace? <pre> </pre> , - .

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

:

<?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);?> 

:

 <code>Hello world!</code>

script , :

( ) , :

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

( ) , :

      $replacement[0]="new_word"; 

!

+1

Source: https://habr.com/ru/post/1757428/


All Articles