0

In PHP, I have a template with HTML and javascript in it :

<script>
  if (a < b) {
    alert(a);
  } 
</script>
<div>
  hello
</div>

This is fed into a DOMDocument with the loadXML method, but this procudes an error because of the < character inside the script. I know I could possibly use the loadHTML method instead, but for now I just need a quick fix that replaces the < character inside the script tags, and then replace it later again with a <

So the question is, what is the best method to replace the < character, but ONLY inside the script tags?

3 Answers 3

6

If you can modify the HTML, the best solution is to wrap your JavaScript code with a CDATA section using the <![CDATA[ and ]]> begin and end markers. That will make the document valid XML so it can be parsed by an XML parser.

<script>
// <![CDATA[

  if (a < b) {
    alert(a);
  } 

// ]]>
</script>
Sign up to request clarification or add additional context in comments.

2 Comments

yeah, I found that myself already... but don't really like it. The templates should be configurable for end-users, and they would probably not understand this... So I'd like to make it a little bit easier for them, by adding these markers automatically or temporarily replace the < characters...
If the template should be configurable by end-users, they should not fiddle with JavaScript code, or should provide such with external files. Unless you specifically need to allow them to write JS, then you should have to separate editable sections; one for HTML only and one for JS only
1

Use a CDATA for your script if you're using an XML parser.

Comments

0

Below there is a way to escape scripts within a given XHTML piece of code.

This code:

<?php

$code = <<<'CODE'
<script>
  if (a < b) {
    alert(a);
  } 
</script>
<div>
  hello
</div>
CODE;

echo preg_replace(
    '@(\<script(?:\s+[^>]*)?\>)([[:alnum:][:punct:][:space:]]+)(\</script\>)@',
    "\\1\n//<![CDATA[\n\\2\n//]]>\n\\3",
    $code);

Produces this:

<script>
//<![CDATA[

  if (a < b) {
    alert(a);
  } 

//]]>
</script>
<div>
  hello
</div>

Comments

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.