0

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]

3 Answers 3

1

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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

thank you. do you know how can I do the same for <pre lang="html"> ... </pre> ?
change the pattern string to |<pre[^>]*+>([^<]*+)</pre>|i
1

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

Comments

1

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)

1 Comment

i think you mean preg_replace_callback

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.