How to automatically replace HTML tags

In this tutorial you will learn how to configure KTML 4 to automatically replace entered or generated HTML tags with ones you want - e.g. replacing <b> with <strong>, or <i> with <em>.

KTML 4 uses a set of definable rules for replacing one tag with another. You can extend this list by defining new rules with the help of the KTML 4 Application Programming Interface documentation.

The KTML 4 API provides two methods that help deal with this situation:

  1. Ktml.addTagReplacementRule("ruleName", "tagToBeReplaced", "tagToBeReplacedWith") - this method allows the user to define a new replacement rule. The method parameters are:

  2. Ktml.replaceTags(string) - this method applies the replacement rules previously defined on the text you pass as parameter. All rules that have been registered with the editor are applied on the text.  The method only has one parameter:

 

In the following example you will modify a page (e.g. .php, .asp file etc.) that already has a KTML 4 control applied to it in order to add a replacement rule: all <h4> tags will be replaced by <p>. Closing tags are replaced automatically.

Before you begin, make sure the page containing the KTML 4 control is correctly configured. To do so, simply load the page in a browser and apply a simple formatting operation on the text. Once you are sure the page works as expected, you can begin altering it:

  1. Open the page file in a text editor (it can even be the Code view in Dreamweaver).

  2. Locate the lines where a new instance for the KTML 4 control is created. It should look like:

    <script>
    // KTML4 Object
    ktml_ktml1 = new ktml('ktml1');
    </script>

             

  3. Create a new line before the closing </script> tag and enter the call to the addTagReplacementRule method. If you have more than one KTML 4 controls on page, or you use a different name, replace the _ktml1 section with your own name. Enter the following code:

    ktml_ktml1.addTagReplacementRule("head2p", "h4", "p");

             

  4. Save the file and upload it to the server if needed.

 

To test the changes:

  1. Load the page in a browser, type some text and set it to the Heading 4 format:


               

  2. The selected format is applied, and even displayed correctly on page:


                 

  3. Switch to Code view, or save the content - or any other action that interacts with the content. Notice that the tags are now replaced:

 

You can use this method if you need to replace any obsolete tags that still get generated, or to enforce compatibility with an accepted set of tags. As a last resort, you can use this method to enforce a part of XHTML compliance (if you cannot use HTML Tidy to have KTML 4 automatically convert code to XHTML).