php从第0个位置替换第一次出现的字符串

Ben*_*Ben 26 php string replace substring

我想在php中搜索并替换第一个单词,如下所示:

$str="nothing inside";
Run Code Online (Sandbox Code Playgroud)

通过搜索将'nothing'替换为'something',并在不使用的情况下替换 substr

输出应该是:'里面的东西'

Mil*_*joo 53

使用preg_replace()限制为1:

preg_replace('/nothing/', 'something', $str, 1);
Run Code Online (Sandbox Code Playgroud)

/nothing/您要搜索的任何字符串替换正则表达式.由于正则表达式始终从左到右进行求值,因此始终与第一个实例匹配.

  • 如果你只是使用通用字符串,这个解决方案有逃避问题,例如if等等在字符串中.http://stackoverflow.com/questions/1252693/php-str-replace-that-only-acts-on-the-first-match有一个更通用的解决方案. (3认同)

mis*_*shu 13

在str_replace的手册页(http://php.net/manual/en/function.str-replace.php)上你可以找到这个函数

function str_replace_once($str_pattern, $str_replacement, $string){

    if (strpos($string, $str_pattern) !== false){
        $occurrence = strpos($string, $str_pattern);
        return substr_replace($string, $str_replacement, strpos($string, $str_pattern), strlen($str_pattern));
    }

    return $string;
}
Run Code Online (Sandbox Code Playgroud)

用法示例:http://codepad.org/JqUspMPx

  • @Ben功能类似,但绝对不一样.如果使用需要通过正则表达式转义的字符,则在使用preg_replace时会出现意外错误. (2认同)