-2

As title, If I have some html <p><span style="font-style:italic">abcde</span><span style="font-weight:bold">abcde</span></p>, I want to strip the style tags and transform them into html tags, so to make it become <p><i>abcde</i><b>abcde</b></p>. How can I do that in PHP?

I notice that when I open the html in CKEditor, this kind of transformation is done automatically. But I want to do it in backend PHP. Thanks.

user2335065
  • 2,337
  • 3
  • 31
  • 54

3 Answers3

-1
$string = '<p><span style="font-style-italic;font-weight:bold">abcde</span><span style="font-weight:bold">abcde</span></p>';

$dom = new DOMDocument();
$dom->loadHTML($string);

$xp = new DOMXPath($dom);

$str = '';
$results = $xp->query('//span');
if($results->length>0){
    foreach($results as $result){
        $style = $result->getAttribute("style");
        $style_arr = explode(";",$style);
        $style_template = '%s';
        if(count($style_arr)>0){
            foreach($style_arr as $style_item){
                if($style_item == 'font-style-italic'){
                    $style_template = '<i>'.$style_template.'</i>';
                }
                if($style_item == 'font-weight:bold'){
                    $style_template = '<b>'.$style_template.'</b>';
                }
            }
        }
        $str .= sprintf($style_template,$result->nodeValue);
    }
}
$str = '<p>'.$str.'</p>';
oatlive
  • 1
  • 1
  • 3
    Welcome to SO. Please explain your answer to improve its quality (see https://stackoverflow.com/help/answering for more). – Alfie Feb 12 '20 at 09:09
-2

You can also use html tags under php parameters or php opening and closing tags like this

<?php
    echo"<h1>Here is Heading h1 </h1>"; 
 ?>

Or you can Put your html code in " " after echo Like this

<?php echo"Your Html Code Here"; ?>

-2
$output = preg_replace('/(<[^>]+) style=".*?"/i', '$1', $input);

Match a < follow by one or more and not > until space came and the style="anything" reached. The /i will work with capital STYLE and $1 will leave the tag as it is, if the tag does not include style="". And for the single quote style='' use this:

(<[^>]+) style=("|').*?("|')
4b0
  • 21,981
  • 30
  • 95
  • 142
SK Developers
  • 29
  • 1
  • 9
  • Not sure if something like *fb/sk.developers for more info* should be part of the answer - if they need more help then that should be done on here (some may consider this SPAM). – Nigel Ren Feb 12 '20 at 06:52