drsvw88664 2014-06-16 09:02
浏览 778
已采纳

使用正则表达式替换第二次出现的子字符串

I have a string with xml formatted like what is shown below.

How can I find the second occurrence of <para> and replace with <para align='left'>?

$str = "<para>From the New York Times</para>

<para>Instacart, a two-year-old grocery delivery company, announced a $44 million round of financing on Monday led by Andreessen Horowitz. Three venture capital firms that previously invested in the company, Sequoia Capital, Khosla Ventures and Canaan Partners, participated in the latest round.</para>

<para>The company, which is based in San Francisco, lets customers shop online from grocery stores in their area. The orders are filled by other people who have signed up to be shoppers and who receive a cut of the delivery fees. Information about a store’s inventory comes from store managers and from the shoppers. The company says it can have groceries delivered within an hour.</para>";
  • 写回答

2条回答 默认 最新

  • doubao6464 2014-06-16 09:08
    关注

    Use a DOM parser with an XPath expression to achieve this. The expression //para[2] will select just the second <para> node. Once you have selected the required node, you can simply alter it however you wish, using the set of available functions that DOMDocument offers. In this case, you can simply use setAttribute() to set the attribute align with a value of left.

    $dom = new DOMDocument;
    
    libxml_use_internal_errors(true); // Disable error reporting
    $dom->loadHTML($str);
    
    $xpath = new DOMXPath($dom);
    
    $secondPara = $xpath->query('//para[2]');
    $secondPara->item(0)->setAttribute('align', 'left');
    
    echo $dom->saveHTML();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

悬赏问题

  • ¥15 全志t113i启动qt应用程序提示internal error
  • ¥15 ensp可以看看嘛.
  • ¥80 51单片机C语言代码解决单片机为AT89C52是清翔单片机
  • ¥60 优博讯DT50高通安卓11系统刷完机自动进去fastboot模式
  • ¥15 minist数字识别
  • ¥15 在安装gym库的pygame时遇到问题,不知道如何解决
  • ¥20 uniapp中的webview 使用的是本地的vue页面,在模拟器上显示无法打开
  • ¥15 网上下载的3DMAX模型,不显示贴图怎么办
  • ¥15 关于#stm32#的问题:寻找一块开发版,作为智能化割草机的控制模块和树莓派主板相连,要求:最低可控制 3 个电机(两个驱动电机,1 个割草电机),其次可以与树莓派主板相连电机照片如下:
  • ¥15 Mac(标签-IDE|关键词-File) idea
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部