Trying to replace parts of string start with same search chars

后端 未结 3 2040
北海茫月
北海茫月 2020-12-02 03:19

I\'m trying to replace parts of my string. But I met a problem when my search string start with same character:

$string = \"Good one :y. Keep going :y2\"; 

         


        
相关标签:
3条回答
  • 2020-12-02 03:36
    :y\b
    

    Use this to replace only :y and not :y2.See demo.

    https://regex101.com/r/sJ9gM7/9

    $re = "":y\\b"m";
    $str = "Good one :y. Keep going :y2\n";
    $subst = "a";
    
    
    $result = preg_replace($re, $subst, $str);
    

    Similarly for :y2 use :y2\b.

    0 讨论(0)
  • 2020-12-02 03:50

    Besides that you should define your array first before you use it, this should work for you:

    $str = strtr($string, $my_array);
    

    Your problem is that str_replace() goes through the entire string and replaces everything it can, you can also see this in the manual.

    And a quote from there:

    Because str_replace() replaces left to right, it might replace a previously inserted value when doing multiple replacements. See also the examples in this document.

    So for this I used strtr() here, because it tries to match the longest byte in the search first.

    You can also read this in the manual and a quote from there:

    If given two arguments, the second should be an array in the form array('from' => 'to', ...). The return value is a string where all the occurrences of the array keys have been replaced by the corresponding values. The longest keys will be tried first. Once a substring has been replaced, its new value will not be searched again.

    0 讨论(0)
  • 2020-12-02 03:54

    Try to replace first for :y2 and then for :y

    $string = "Good one :y. Keep going :y2"; 
    
    $my_array= array(":y2" => "b", ":y" => "a");
    
    $str = str_replace(array_keys($my_array), array_values($my_array), $string);
    

    outputs

    Good one a. Keep going b
    

    Try it

    0 讨论(0)
提交回复
热议问题