0

The message is submited via form. It can contain html as well as normal text.

i.e.:

Why this code doesn't work for me?

<script type="text/javascript">
    var _gaq = _gaq || [];

    _gaq.push(['_setAccount', 'UA-XXXXX-X']);

    _gaq.push(['_trackPageview']);

    (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
    })();
</script>

I would like to surround html element with pre tag.

i.e.

Why this code doesn't work for me?

<pre>
    <script type="text/javascript">
        var _gaq = _gaq || [];

        _gaq.push(['_setAccount', 'UA-XXXXX-X']);

        _gaq.push(['_trackPageview']);

        (function() {
            var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
            ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
            var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
        })();
    </script>
</pre>

I asked earlier about it in php chat room and author of the answer in this question suggested to read the solution: php DOMDocument: complete transform of form element? wrapping and removing?

Everything is perfect in this example exept few things. I need to wrap any html element obviously exept pre itself.

  1. If elements are folded, then wrap only outer element.
  2. If they are separate, then wrap each of them.
  3. If there is only open tag, then wrap it only(no need of fixing with close tag).

Does anyone have any possible idea for a solution to this question? Thanks in advance to all who can help.

Community
  • 1
  • 1
Eugene
  • 4,352
  • 8
  • 55
  • 79
  • This may or may not directly address your problem but I've used HTMLPurifier (htmlpurifier.org) in the past any time I had to deal with HTML being submitted. – Benny Hill Feb 01 '13 at 14:11

1 Answers1

0

I am not sure how well DOMDocument handles HTML that is not well formed. And if the message contains closing tags without opening tags you will probably get errors. But I think you will get the idea from the following...

Wrap the whole message into e.g. a div to make it parseable. Then load the string into a DOMDocument. Use DOMXPath like in the linked answer to find the top most elements inside the div you created and wrap those with pre:

$dom = new DOMDocument();
$dom->loadHTML("<div>$msg</div>");

$xpath = new DOMXPath($dom);
$query = $xpath->query("body/div/*");
hsan
  • 1,560
  • 1
  • 9
  • 12