douhe4336 2013-11-25 10:23
浏览 67
已采纳

PHP RegEx替换

I'm trying to write a PHP Script that replaces auto-generated Content from a WordPress Plugin. The Plugin isn't able to provide a WYSIWYG Editor for special fields but it can recognize new lines. My Output would look like this:

Some Text that has to
go over a few
lines of code
because it's actually supposed to be a list

when the client writes inside these field all lines get <br> tags at the end, so I tried to find and replace them with </li> tags as well as adding a <li> in front of every new line. My PHP Script looks like this:

 $text = types_render_field("field-name");

 $pattern = array();
 $pattern[0] = "/br/"; // br tags
 $pattern[1] = "/
/"; // new lines
 $replacements = array();
 $replacements[0] = "/li"; // replacement for <br>
 $replacements[1] = "<li>"; // insert into every new line (
)

 echo "<ul>"; // wrapping the <li>'s
 echo preg_replace($pattern, $replacements, $text);
 echo "</ul>";

It's actually working so far but the first line get's no <li> in front of it so my question is: How do I get a <li> in front of the first line?

  • 写回答

2条回答 默认 最新

  • duancilan5124 2013-11-25 10:26
    关注

    Keep it simple. Instead of

    echo "<ul>"; // wrapping the <li>'s
    

    Use:

    echo "<ul><li>"; // wrapping the <li>'s
    

    OR else:

    Instead of:

    $pattern[1] = "/
    /"; // new lines
    

    Use:

    $pattern[1] = "/^|
    /"; // new lines OR start
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥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)