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


php replace first occurrence of string from 0th position

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

$str="nothing inside";

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

输出应该是:"something internal"

使用限制为1:的preg_replace()

preg_replace('/nothing/', 'something', $str, 1);

将正则表达式/nothing/替换为要搜索的任何字符串。由于正则表达式总是从左到右求值,因此这将始终与第一个实例匹配。

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;
}

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

尝试这个

preg_replace('/^[a-zA-Z]'s/', 'ReplacementWord ', $string)

它所做的是选择从开始到第一个空白的任何内容,并将其替换为replcementWord。注意replcementWord后面有一个空格。这是因为我们在搜索字符串

中添加了's
preg_replace('/nothing/', 'something', $str, 1);

我遇到了这个问题,想要一个解决方案,但这对我来说不是100%正确的,因为如果字符串像$str = "mine'this,那么灾难就会导致问题。所以我想出了一个小把戏:

$stick='';
$cook = explode($str,$cookie,2);
        foreach($cook as $c){
            if(preg_match("/^'/", $c)||preg_match('/^"/', $c)){
                //we have 's dsf fds... so we need to find the first |sess| because it is the delimiter'
                $stick = '|sess|'.explode('|sess|',$c,2)[1];
            }else{
                $stick = $c;
            }
            $cookies.=$stick;
        }

这会检查并缓存一个命令中的第一个子字符串位置,然后替换它(如果存在),应该是更紧凑、更高性能的:

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

这个函数str_replace就是您要查找的函数。

ltrim()将删除字符串开头不需要的文本。

$do = 'nothing'; // what you want
$dont = 'something'; // what you dont want
$str = 'something inside';
$newstr = $do.ltrim( $str , $dont);
echo $newstr.'<br>';