dougan1465 2017-09-24 01:40
浏览 22
已采纳

PHP,从数据库处理字符串,更改<p>

I'm trying to something really easy but I'm confused...

I'm getting a string in php (from a database) that looks like this when Inspect the element with chrome (also in the database, the string is like this) :

$text=

    <p><strong>Title</strong></p>
    <p>text1</p>
    <p>text2</p>
    <p>text3</p>
    <p>text4</p>
    <p><strong>Title2</strong></p>
    .....

I would like to change all the <p> to <p class ="newclass"> and show the text in the browser in the right way.

I tried different ways like this one:

$newtext = preg_replace('/\b<p>\b/u', '<p class = "newclass">', highlight_string($text, true));
echo $newtext;

but that doesn't works. I tried more example but all of theme didn't works.

So, basically I'm getting some text from a database, and I need to change all <p> to a specific new class and echo again in the right way.

Thank you very much

  • 写回答

1条回答 默认 最新

  • douya2007 2017-09-24 01:55
    关注

    You can use substr_replace to accomplish this task. It is fairly simple.

    $text = '<p>';
    $class = ' class="class_name">';
    
    echo substr_replace($text, $class, -1);
    

    This code will take the original string, $text, substract -1 from it, and add the second string, $class, to the end of your string (in this case it will be before the >).

    The first param is the original string, the one you are pulling from the database, with <p>.

    The second param is the addition to the string you are wanting to, and you can change it to reflect whatever need you have.

    The third param is the position of where to add the text. You note that the number is negative, this will mean that the script will look for the end of the string to add the extra content, if you change it to a positive number it will start from the beginning.

    start

    If start is non-negative, the replacing will begin at the start'th offset into string.

    If start is negative, the replacing will begin at the start'th character from the end of string.

    PHP's documentation & syntax

    mixed substr_replace ( mixed $string , mixed $replacement , mixed $start [, mixed $length ] )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 我的R语言提示去除连锁不平衡时clump_data报错,图片以下所示,卡了好几天了,苦恼不知道如何解决,有人帮我看看怎么解决吗?
  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序