douwen1313 2016-06-08 11:55
浏览 89
已采纳

如何在模式中的preg_replace中使用变量?

I have XML in string like this:

<a:b>
  <a:c></a:c>
  <a:c></a:c>
</a:b>

and I would like to remove all data inside namespace 'a'.

Of course this can be done this way:

/<\ba\b:.*?>.*?<\/\ba\b:.*?>/

But in this case result is:

  <a:c></a:c>
</a:b>

because the first closing tag for namespace 'a' is actually a child element. So doing it recursively would live '' inside my string.

So the idea I had was to use variable in pattern the same way as you can use it in replacement:

/<(\ba\b:.*?)>.*?<\/$1>/

This is a non working solution used just to represent the idea of realisation.

All your help, ideas, ... are very welcome. Thank you for your answer in advance.

  • 写回答

1条回答 默认 最新

  • doutou3725 2016-06-08 12:38
    关注

    To directly answer the question, here is a reduced working example :

    (?P<nodeOpen><a:(?P<nodeName>.*)>)(?P<data>.*)(?P<nodeClose><\/a:(?P=nodeName)>)
    

    Used in php code :

    preg_match('#(?P<nodeOpen><a:(?P<nodeName>.*)>)(?P<data>.*)(?P<nodeClose><\/a:(?P=nodeName)>)#s', $xml, $matches);
    
    /* Produce :
    
    array(9) {
      [0]=>
      string(43) "<a:b>
      <a:c></a:c>
      <a:c></a:c>
    </a:b>"
      ["nodeOpen"]=>
      string(5) "<a:b>"
      [1]=>
      string(5) "<a:b>"
      ["nodeName"]=>
      string(1) "b"
      [2]=>
      string(1) "b"
      ["data"]=>
      string(32) "
      <a:c></a:c>
      <a:c></a:c>
    "
      [3]=>
      string(32) "
      <a:c></a:c>
      <a:c></a:c>
    "
      ["nodeClose"]=>
      string(6) "</a:b>"
      [4]=>
      string(6) "</a:b>"
    }
    
    */
    

    And then concat :

    $emptyNode = $matches['nodeOpen'] . $matches['nodeClose'];
    

    Can be consulted live here : https://regex101.com/r/xX1uZ9/2

    I also recommend you the awesome talk of the amazing spiderman Jordi Boggiano available on youtube ( https://www.youtube.com/watch?v=ayo8zDnd-m8 )

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图2.0 版本点聚合中Marker的位置无法实时更新,如何解决呢?
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题