2017-07-17 73 views
0

我必須替換URL中的字符,但只能形成某個點,並且還要處理重複字符。在某個字符/單詞之後替換字符,但跳過第一個匹配並處理重複

的網址是這樣的:

http://example.com/001-one-two.html#/param-what-ever 
http://example.com/002-one-two-three.html#/param-what--ever- 
http://example.com/003-one-two-four.html#/param2-what-ever- 
http://example.com/004-one-two-five.html#/param33-what--ever---here- 

,他們應該是這樣的:

http://example.com/001-one-two.html#/param-what_ever 
http://example.com/002-one-two-three.html#/param-what_ever_ 
http://example.com/003-one-two-four.html#/param2-what_ever_ 
http://example.com/004-one-two-five.html#/param33-what_ever_here_ 

在口頭上與單個_字符替換-字符(任意數量的話),但跳過第一個-之後​​
​​之後的字符串長度變化很明顯,我找不到一種方法來做到這一點。

我該怎麼做?

+0

讓我們瞭解您到目前爲止試過。 –

+0

strreplace找到'#/'後找到一個數組,但是沒有成功。 –

回答

0

這裏有很長的路要走,使用preg_replace_callback

$in = array(
'http://example.com/001-one-two.html#/param-what-ever', 
'http://example.com/002-one-two-three.html#/param-what--ever-', 
'http://example.com/003-one-two-four.html#/param2-what-ever-', 
'http://example.com/004-one-two-five.html#/param33-what--ever---here-' 
); 

foreach($in as $str) { 
    $res = preg_replace_callback('~^.*?#/[^-]+-(.+)$~', function ($m) { 
       return preg_replace('/-+/', '_', $m[1]); 
      }, 
      $str); 
    echo "$res\n"; 
} 

說明:

~   : regex delimiter 
^  : start of string 
    .*?  : 0 or more any character, not greedy 
    #/  : literally #/ 
    [^-]+ : 1 or more any character that is not a dash 
    -  : a dash 
    \K  : forget all we have seen until here 
    (.+) : group 1, contains avery thing after the first dash after #/ 
    $   : end of string 
~   : regex delimiter 

輸出:

http://example.com/001-one-two.html#/param-what_ever 
http://example.com/002-one-two-three.html#/param-what_ever_ 
http://example.com/003-one-two-four.html#/param2-what_ever_ 
http://example.com/004-one-two-five.html#/param33-what_ever_here_ 
相關問題