【问题标题】:How to using preg_replace() remove value duplicate from an URL如何使用 preg_replace() 从 URL 中删除重复值
【发布时间】:2014-09-12 04:03:14
【问题描述】:

我有一个简单的网址:

http://sample.com/?page=1&page=2
http://sample.com/?page=2&page=1

如何使用 preg_replace() 删除重复值(页面)

这是代码:

$link = preg_replace("/\b(\w+)\s+\\1\b/i", "$1", $link );

但是结果是错误的,我该如何修复它,结果看起来像:

http://sample.com/?page=1&page=2 => http://sample.com/?page=2
http://sample.com/?page=2&page=1 => http://sample.com/?page=1

【问题讨论】:

    标签: php regex preg-replace


    【解决方案1】:

    您可以考虑递归子模式而不是尝试使用反向引用。

    $link = 'http://sample.com/?page=1&page=2';
    $link = preg_replace('/\b(\w+=\d+)&((?1))/', '$2', $link);
    echo $link; //=> "http://sample.com/?page=2"
    

    我想你可以使用反向引用:

    $link = preg_replace('/\b(\w+=)\d+&(\1\d+)/', '$2', $link);
    

    【讨论】:

      【解决方案2】:

      替换:

      \?.*?\K([^=]+)(?:=[^&]*)?&(.*)\1=(.*?)(?:&|$)
      

      与:

      \2\1=\3
      

      Demo


      \?      (?# match ? literally)
      .*?     (?# lazily match unnecessary params)
      \K      (?# throw away everything to the left)
      ([^=]+) (?# capture 1+ non-= characters)
      (?:     (?# start non-capturing group)
        =     (?# match = literally)
        [^&]* (?# match 0+ non-& characters)
      )?      (?# end optional parameter value)
      &       (?# match & literally)
      (.*)    (?# capture optional inbetween junk)
      \1     (?# a paramater that has already been seen in capture group 1)
      =       (?# literally match =)
      (.*?)   (?# lazily capture the newest value)
      (?:     (?# begin non-capturing group)
        &     (?# literally match &)
       |      (?# OR)
        $     (?# match the end of the URL)
      )       (?# end non-capturing group)
      

      【讨论】:

        猜你喜欢
        • 2014-05-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-02
        • 1970-01-01
        相关资源
        最近更新 更多