How to apply htmlspecialchars() to selected substrings

Hi
I would like to be able to process, with htmlspecialchars(), certain sections of a text string which is read from a MySQL text field. I have all the basic CRUD elements working. The text string contains text, html formating, links to jpeg files etc. It also contains examples of html code. My goal is to have the page rendered correctly for the text and images (this already works). I also know how to store and retrieve strings as un-rendered html code and display it as code using htmlspecialchars (thanks to you guys). But now I want my page to contain both content and actual code examples - my idea is to tag my code examples by simply starting and finishing the sections with something like

**start** and **finish**.

Now my problem is how to replace all substrings between every **start** and **finish** with the htmlspecialchars() of the same substring?

For example -
Hello this is my <b>blog</b> and here are some code examples **start**<b>hello world</b> **finish** this is how you specify a heading **start**<h1>Here is a heading</h1>**finish** thank you
Would be changed to -
Hello this is my <b>blog</b> and here are some code examples **start** gt;hello world&amp;lt;/b&amp;gt; this is how you specify a heading **start** &amp;lt;h1&amp;gt;Here is a heading&amp;lt;/h1&amp;gt;**finish** thank you

Basically in psuedo code:-
for every $substring between **start** and **finish** in $text
$new string = htmlencode($substring)
replace $substring with $newstring

I have looked at preg_match and preg_replace and str_replace but i am having trouble running a PROCESS on all instances of a substring BETWEEN 2 substrings. I really want to keep the process as code rather than just a built in PHP function as I can foresee I may have to append some code at some time to preserve formatting, particularly <br>.

Thanks in advance guys

maybe misleading, but why don’t you just

Use <code> for inline code that can wrap and <pre><code> for block code that must not wrap.

1 Like
Sponsor our Newsletter | Privacy Policy | Terms of Service