drsvw88664 2014-06-16 17:02
浏览 777
已采纳

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

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 17: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 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制