drsvw88664 2014-06-16 17: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 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 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配