I'd like to change <pre>
with <code>
and </pre>
with </code>
.
I'm having problem with the slash / and regex.
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.
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.
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.
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);
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With