Remove div tags

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
serpisor
Forum Newbie
Posts: 1
Joined: Tue Apr 08, 2008 1:32 am

Remove div tags

Post by serpisor »

I need a php function that will remove all div tags except

Code: Select all

<div align="left"><div align="center"><div align="right"><div align="justify">
Input example 1:

Code: Select all

<div align="right"><div class="class"><div align="right" class="class">some text</div></div></div>
Output example 1:

Code: Select all

<div align="right">some text</div>
Input example 2:

Code: Select all

<div align="right">some text</div></div></div></div>
Example output 2:

Code: Select all

<div align="right">some text</div>
Example input 3:

Code: Select all

<div align="right"><div align="right"><div align="right"><div align="right">some text
Output example 3:

Code: Select all

some text
Some text may contain other html tags except the div ones.

Thank you!
aCa
Forum Newbie
Posts: 11
Joined: Sun Apr 06, 2008 3:43 pm

Re: Remove div tags

Post by aCa »

Hmm, I problems figure out a pretty way to do this. Hopefully somone have a pretty way to do this, better then my way :-)

Ok first take and remove temperarly the divs you wan't to keep.

Code: Select all

 
preg_replace('/<div align="right">(.*)<\/div>/U', 'DIVRIGHTSTART$1DIVRIGHTEND', $string);
preg_replace('/<div align="center">(.*)<\/div>/U', 'DIVCENTERSTART$1DIVCENTEREND', $string);
preg_replace('/<div align="left">(.*)<\/div>/U', 'DIVLEFTSTART$1DIVLEFTEND', $string);
preg_replace('/<div align="justify">(.*)<\/div>/U', 'DIVJUSTIFYSTART$1DIVJUSTIFYEND', $string);
 
Then remove the remaining divs, including the end divs.

Code: Select all

 
preg_replace('/<\/?div[^>]*>/', '', $string);
 
Then you can use str_replace to change the temp values back to the correct div value. An extrabonus is that you can skip using the old align="" value and use style="text-align:right" etc instead :-)

I know this isn't pretty but it should work...

Good luck! :-)
Post Reply