Page 1 of 1

Using htmlentities() in preg_replace()

Posted: Sun Oct 08, 2006 1:57 pm
by HiddenS3crets
I'm trying to run the htmlentities() function inside a preg_replace() like so:

Code: Select all

preg_replace("<code>(.*)</code>", "<code>".htmlentities(\\1)."</code>", $tutorial);
Basically this line is supposed to replace anything between <code> and </code> with the htmlentities() output.

Example:
- Before function

Code: Select all

<code><?php echo "hello world"; ?></code>
- After function

Code: Select all

<code><php echo "hello world"; ?></code>
I'm getting the error of an unexpected character, the two '\' I use inside htmlentities(). I don't know how else to use the backreference. Any ideas?

Posted: Sun Oct 08, 2006 2:14 pm
by volka

Code: Select all

<?php
$tutorial = '<code><b>yadda</b></code>';

$pattern = '!<code>(.*)</code>!Use';
$replace = '"<code>".htmlentities(\'$1\')."</code>";';

echo preg_replace($pattern, $replace, $tutorial);
?>
or

Code: Select all

<?php
function cbHtmlentities($a) {
	return htmlentities($a[1]);
}

$tutorial = '<code><b>yadda</b></code>';

$pattern = '!(?<=<code>)(.*)(?=</code>)!Us';
echo preg_replace_callback($pattern, 'cbHtmlentities', $tutorial);
?>
I avoid eval() if there's no very good reason for it and preg_match(/.../e) as well.
Therefore I prefer the preg_replace_callback version.