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 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输