Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: using preg_replace with htmlentities

Tags:

regex

php

I'm writing an RSS to JSON parser and as a part of that, I need to use htmlentities() on any tag found inside the description tag. Currently, I'm trying to use preg_replace(), but I'm struggling a little with it. My current (non-working) code looks like:

$pattern[0] = "/\<description\>(.*?)\<\/description\>/is";
$replace[0] = '<description>'.htmlentities("$1").'</description>';
$rawFeed = preg_replace($pattern, $replace, $rawFeed);

If you have a more elegant solution to this as well, please share. Thanks.

like image 439
VirtuosiMedia Avatar asked Dec 07 '25 04:12

VirtuosiMedia


1 Answers

Simple. Use preg_replace_callback:

function _handle_match($match)
{
    return '<description>' . htmlentities($match[1]) . '</description>';
}

$pattern = "/\<description\>(.*?)\<\/description\>/is";
$rawFeed = preg_replace_callback($pattern, '_handle_match', $rawFeed);

It accepts any callback type, so also methods in classes.

like image 111
Armin Ronacher Avatar answered Dec 08 '25 18:12

Armin Ronacher



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!