Using htmlentities() in preg_replace()

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
HiddenS3crets
Forum Contributor
Posts: 119
Joined: Fri Apr 22, 2005 12:23 pm
Location: USA

Using htmlentities() in preg_replace()

Post 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?
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post 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.
Post Reply