Alex
Alex

Reputation: 68084

PHP - convert code section from a string to html characters

I have string like this:

<a href="http://google.com"> link </a>
[code lang="html" anotherargument="foo"...]
<a href="http://google.com"> link </a>
[/code]

How can I convert the code wrapped between [code...] and [/code] to HTML characters?

like this:

<a href="http://google.com"> link </a>
[code lang="html" anotherargument="foo"...]
&lt;a href=&quot;http://google.com&quot;&gt; link &lt;/a&gt;
[/code]

Upvotes: 0

Views: 856

Answers (3)

chriso
chriso

Reputation: 2552

Try this

preg_match_all('`\[code[^\]]*+]([^\[]*+)\[/code\]`i', $html, $matches, PREG_SET_ORDER);

foreach ($matches as $match) {
    $html = str_replace($match[1], htmlentities($match[1]), $html);
}

Upvotes: 1

Billy Moon
Billy Moon

Reputation: 58619

You could use regular expressions with a callback - so match the what is between code tags, then replace by running through a function.

Something like this untested code:

$str = preg_replace_callback('/(\[code.+?\])(.+?)(\[\/code\])/', create_function(
            '$m',
            'return $m[1] . htmlentities($m[2]) . $m[3];'
        ),$str)

Upvotes: 1

Bjoern
Bjoern

Reputation: 16314

I think htmlspecialchars or htmlentities have the functionality you are looking for. Both convert characters to HTML entities.

Upvotes: 1

Related Questions