duan19911992 2015-04-28 12:06
浏览 178

将<br />转换为<p>标签以标准化文本

I have a HTML that is in various formats and I'm trying to standardize the code using PHP. In some cases I receive it using breaks
to separate lines. I need these to be <p> tags instead.

1- For fist step I try to split the text by <br> and add it to new holder

<?php

$text = 'I am <br><br>       <br><p> <br>your firnd <br></p><p>   </p> ok?';
$breaks = array("<br />","<br>","<br/>","<p>","</p>");  
$text = str_ireplace($breaks, "<br>", $text); 
echo "R1: ".htmlspecialchars($text, ENT_QUOTES, "UTF-8");
$text = explode("<br>", $text);
$newText = null;
for($i=0; $i < count($text) ;$i++)
{
    if(!empty($text[$i]))
        $newText .= "<p>".$text[$i]."</p>";
}


$breaks = array("<p></p>","<p> </p>","<p> </p>");  

echo "<br/>R2: ".htmlspecialchars($newText, ENT_QUOTES, "UTF-8");

$newText = str_ireplace($breaks, "", $newText); 

echo "<br/>R3: ".htmlspecialchars($newText, ENT_QUOTES, "UTF-8");
?>

Result:

R1: I am <br><br> <br><br> <br>your firnd <br><br><br> <br> ok?
R2: <p>I am </p><p> </p><p> </p><p>your firnd </p><p> </p><p> ok?</p>
R3: <p>I am </p><p> </p><p>your firnd </p><p> </p><p> ok?</p>

Do you a suggestion for me to improve this code? Also I have 2 issue whit that...

And how can avoid generate extra <p></p> in my code and also how can remove attributes of p (id,class,meta,etc...) in p tag?

for example for this example:

$text = 'I am <br><br>       <br><p id="ids" class="classes" meta-name="test"> <br>your firnd <br></p><p>   </p> ok?';
  • 写回答

1条回答 默认 最新

  • dter8514 2015-04-28 12:13
    关注

    try this:- using preg_replace() and str_replace()

    <?php
    $text = 'I am <br><br><br><p id="ids" class="classes" meta-name="test"> <br>your firnd <br></p><p>   </p> ok?';
    $newcontent = preg_replace("/<b[^>]*?>/", "", $text);
    echo $newcontent = str_replace("</b>", "<p />", $newcontent);
    
    评论

报告相同问题?

悬赏问题

  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示