How to use php preg_replace to replace HTML tags

前端 未结 3 1447
执念已碎
执念已碎 2020-12-17 04:11

I\'d like to change

 with  and 
with .

I\'m having problem with t

相关标签:
3条回答
  • 2020-12-17 04:17

    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);
    
    0 讨论(0)
  • 2020-12-17 04:27

    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.

    0 讨论(0)
  • 2020-12-17 04:27

    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!

    0 讨论(0)
提交回复
热议问题