0

Je dois remplacer les caractères dans les URL, mais ne forme qu'un certain point et gère également les caractères dupliqués.Remplacer un caractère après un certain caractère/mot mais ignorer la première correspondance et gérer également les doublons

Les URL ressemblent à ceci:

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- 

et ils devraient ressembler à ceci:

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_ 

En mots remplacer - caractères (un nombre quelconque de celui-ci) avec un seul _ omble chevalier, mais sauter la premier - après #/
La longueur de la chaîne après le #/ varie évidemment et je ne pouvais pas trouver un moyen de le faire.

Comment est-ce que je peux faire ceci?

+0

Montrez-nous ce que vous avez essayé jusqu'à présent . –

+0

strreplace avec un tableau après avoir trouvé '# /' mais cela n'a pas fonctionné. –

Répondre

0

Voici un chemin à parcourir, en utilisant 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"; 
} 

Explication:

~   : 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 

Sortie:

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_