Issue
I want to convert my html strings which contain <p style=“text-align:center; others-style:value;”>Content</p>
to <center>Content</center>
, and <p style=“text-align:right; others-style:value;”>Content</p>
to <right>Content</right>
etc.
My previous question has an answer which can achieve this perfectly. Which is regex is:
$RegEx = '/<(.*)(text-align:)(.*)(center|left|right|justify|inherit|none)(.*)(\"|\”|\'|\’)>(.*)(<\/.*)/s';
$string = preg_replace($RegEx, '<$4>$7</$4>', $string);
However, my strings may contain more than one occurrences of the text-align. For example, I might have <div style=‘text-align:left; others-style:value;’ class=‘any class’>Any Content That You Wish</div><p style=“text-align:center; others-style:value;”>Content</p>
I want it to become <left>Any Content That You Wish</left><center>Content</center>
, but it would just output <center>Content</center>
.
How can I get what I want in PHP? Many thanks.
Solution
As I wrote in the comments, you should not use regex for manipulating html content. But only if you have non-nested tags in your html, you can go for it.
For this particular case, you can use this regex,
<(p|div).*?\bstyle\s*=\s*.*?text-align:([a-zA-Z]+).*?>(.*?)</\1>
And replace it with <\2>\3</\2>
$html = '<p style=“text-align:center; others-style:value;”>Content</p>
<div style=‘text-align:left; others-style:value;’ class=‘any class’>Any Content That You Wish</div><p style=“text-align:center; others-style:value;”>Content</p>';
$newhtml = preg_replace("~<(p|div).*?\bstyle\s*=\s*.*?text-align:([a-zA-Z]+).*?>(.*?)</\\1>~", '<\2>\3</\2>', $html);
echo $newhtml;
Prints,
<center>Content</center>
<left>Any Content That You Wish</left><center>Content</center>
Answered By - Pushpesh Kumar Rajwanshi Answer Checked By - Cary Denson (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.