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 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)