【问题标题】:How to change first occurrence of word in a string如何更改字符串中单词的第一次出现
【发布时间】:2012-01-06 12:15:59
【问题描述】:

如何更改字符串中单词的第一次出现?

例子:

$a = "Yo! **Hello** this is the first word of Hello in this sentence";

$b = "Yo! **Welcome** this is the first word of Hello in this sentence";

【问题讨论】:

    标签: php string replace


    【解决方案1】:

    这行得通,虽然效率有点低:

    $a = "Yo! **Hello** this is the first word of Hello in this sentence";
    $a = preg_replace('/Hello/', 'Welcome', $a, 1);
    

    另一个流行的答案:

    $b = str_replace('Hello', 'Welcome', $a, 1);
    

    不起作用。 str_replace 的第四个参数应该是一个变量,它通过引用传递,str_replace 会将其设置为替换次数

    更好的解决方案是从输入字符串中提取两个子字符串:

    1. 第一次出现Hello之前的子字符串,叫它$s1
    2. 第一次出现Hello后的子串,称它为$s2

    可以使用strpos获取位置。

    结果是$s1.'Welcome'.$s2

    【讨论】:

    • 刚刚看到您的编辑 - 我已经实施了您的第二个解决方案并将其发布为答案:)
    • 看到低效的答案...在生产代码中使用它。为什么?比第二个提议的解决方案更容易理解:)
    【解决方案2】:

    只需将substrstrpos 一起使用两次。

    $a = "Yo! **Hello** this is the first word of Hello in this sentence";
    $search = "Hello";
    $replacement = "Welcome";
    $b = substr( $a, 0, strpos( $a, $search)) . $replacement . substr( $a, strpos( $a, $search) + strlen( $search));
    

    Demo

    【讨论】:

      【解决方案3】:

      这对于紧凑性和性能来说是最好的:

      if(($offset=strpos($string,$replaced))!==false){
         $string=substr_replace($replaced,$replacer,$offset,strlen($replaced));
      }
      

      只替换第一次出现而不重载正则表达式

      【讨论】:

      • 我尝试使用这个,例如 $string = 'the quick brown fox eats the brown sugar.'; $replaced = 'brown'; $replacer = 'yellow'; 。我得到的结果: brownyellow 。我想要的结果:敏捷的黄狐吃红糖。对不起,我错过了什么吗?谢谢
      【解决方案4】:

      使用substr_replace()

      【讨论】:

        【解决方案5】:

        使用str_replace('Hello','Welcome',$a,1);

        【讨论】:

        • 否:“如果通过,这将设置为执行的替换次数。”
        【解决方案6】:

        构建它:

        function str_replace_first($search, $replace, $source) {
        
          $explode = explode( $search, $source );
          $shift = array_shift( $explode );
          $implode = implode( $search, $explode );
          return $shift.$replace.$implode;
        
        }
        

        叫它:

        $msg = "Yo! **Hello** this is the first word of Hello in this sentence";
        echo str_replace_first( 'Hello', 'Welcome', $msg );
        

        试试看:

        http://sandbox.onlinephpfunctions.com/code/399ec70333832423c79d36a42032124d5c296d27

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-06-08
          • 2015-04-27
          • 1970-01-01
          • 1970-01-01
          • 2013-10-04
          相关资源
          最近更新 更多