views:

51

answers:

1

Hi guys,

I am using TinyMCE to publish content to my site. I have the problem whereby I can only insert an image inside another element, eg a paragraph, even if I place the cursor at the end of the content.

So, when I publish the content, I currently end up with markup like:

<p>Text content <img src="blah" /></p><p>Another paragraph</p>

I notice that WordPress and the TinyMCE example site both insert images in the above manner.

I have been unable to find a solution as to how I can insert an image in TinyMCE outside of any other element, so my next step is to try and alter the content server side so that when I publish my content, I am able to correct the markup before saving it to my db, so that I would end up with:

<p>Text content</p><img src="blah" /><p>Another paragraph</p>

Does any body know what I would need to do to achieve this. I know regex should work, but I am not sure what or how to use it to that effect. Even better, if anybody has a solution to the TinyMCE problem, that would be even better.

I know I can obviously use JS to achieve this client side on the fly, but that solution is not ideal.

Many thanks,

D

+2  A: 

Don't use RegEx for manipulating HTML nodes! It's not designed for it and is too fragile.

HTML is not a Regular language, and even with the non-Regular features many modern Regular Expression implementations support, trying to manipulate HTML with a regex is still difficult at best.


For a quick-and-dirty solution, you can do:

preg_replace
    ( "/(<img[^>]++>)\s*+(</p>)/gi"
    , "$2$1"
    , $HtmlText
    );


But that will fail with several valid HTML constructs - what you should actually be using is something like PHP Simple HTML DOM Parser to parse the HTML text into a HTML DOM, manipulate that DOM, and then output as text again.

Peter Boughton
Thanks, Peter. I will look into that.Dave
Dashman