Using str_replace so that it only acts on the first match?

后端 未结 22 1193
醉酒成梦
醉酒成梦 2020-11-22 11:03

I want a version of str_replace() that only replaces the first occurrence of $search in the $subject. Is there an easy solution to thi

22条回答
  •  遥遥无期
    2020-11-22 11:41

    I wondered which one was the fastest, so I tested them all.

    Below you will find:

    • A comprehensive list of all the functions that have been contributed onto this page
    • Benchmark testing for each contrubution (average execution time over 10,000 runs)
    • Links to each answer (for the full code)

    All functions were tested with the same settings:

    $string = 'OOO.OOO.OOO.S';
    $search = 'OOO'; 
    $replace = 'B';
    

    Functions that only replace the first occurrence of a string within a string:

    • substr_replace($string, $replace, 0, strlen($search));

      [CONTRIBUTED BY] => zombat
      [OOO.OOO.OOO.S] => B.OOO.OOO.S
      [AVERAGE TIME] => 0.0000062883
      [SLOWER BY] => FASTEST
      
    • replace_first($search, $replace, $string);

      [CONTRIBUTED BY] => too much php
      [OOO.OOO.OOO.S] => B.OOO.OOO.S
      [AVERAGE TIME] => 0.0000073902
      [SLOWER BY] => 17.52%
      
    • preg_replace($search, $replace, $string, 1);

      [CONTRIBUTED BY] => karim79
      [OOO.OOO.OOO.S] => B.OOO.OOO.S
      [AVERAGE TIME] => 0.0000077519
      [SLOWER BY] => 23.27%
      
    • str_replace_once($search, $replace, $string);

      [CONTRIBUTED BY] => happyhardik
      [OOO.OOO.OOO.S] => B.OOO.OOO.S
      [AVERAGE TIME] => 0.0000082286
      [SLOWER BY] => 30.86%
      
    • str_replace_limit($search, $replace, $string, $count, 1);

      [CONTRIBUTED BY] => bfrohs - expanded renocor
      [OOO.OOO.OOO.S] => B.OOO.OOO.S
      [AVERAGE TIME] => 0.0000083342
      [SLOWER BY] => 32.54%
      
    • str_replace_limit($search, $replace, $string, 1);

      [CONTRIBUTED BY] => renocor
      [OOO.OOO.OOO.S] => B.OOO.OOO.S
      [AVERAGE TIME] => 0.0000093116
      [SLOWER BY] => 48.08%
      
    • str_replace_limit($string, $search, $replace, 1, 0);

      [CONTRIBUTED BY] => jayoaK
      [OOO.OOO.OOO.S] => B.OOO.OOO.S
      [AVERAGE TIME] => 0.0000093862
      [SLOWER BY] => 49.26%
      

    Functions that only replace the last occurrence of a string within a string:

    • substr_replace($string, $replace, strrpos($string, $search), strlen($search));

      [CONTRIBUTED BY] => oLinkSoftware - modified zombat
      [OOO.OOO.OOO.S] => OOO.OOO.B.S
      [AVERAGE TIME] => 0.0000068083
      [SLOWER BY] => FASTEST
      
    • strrev(implode(strrev($replace), explode(strrev($search), strrev($string), 2)));

      [CONTRIBUTED BY] => oLinkSoftware
      [OOO.OOO.OOO.S] => OOO.OOO.B.S
      [AVERAGE TIME] => 0.0000084460
      [SLOWER BY] => 24.05%
      

提交回复
热议问题