PHP替换字符串的第一次出现,从第0位

问题描述:

我想搜索和PHP中的另一个替换的第一个字就像如下:PHP替换字符串的第一次出现,从第0位

$str="nothing inside"; 

通过搜索替换“什么”到“东西”,并且不使用替代substr

输出应该是:“里面的东西”

+0

为什么没有substr? – lfxgroove 2012-03-07 09:27:37

+1

[使用str \ _replace以便它只对第一个匹配起作用]的可能的重复?(http://*.com/questions/1252693/using-str-replace-so-that-it-only-acts-on - 第一次匹配) – Bas 2015-04-24 14:08:25

使用preg_replace()为1的限制:

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

更换正则表达式/nothing/您要搜索的任何字符串。由于正则表达式总是从左到右进行计算,因此它将始终与第一个实例匹配。

+3

如果您只是使用通用字符串,则此解决方案存在转义问题,例如$和$等字符串在该字符串中。 http://*.com/questions/1252693/php-str-replace-that-only-acts-on-the-first-match有一个更通用的解决方案。 – Anther 2012-10-17 18:55:37

This function str_replace是你正在寻找的人。

+6

第4个参数计数替换次数,不限制替换次数 – mishu 2012-03-07 09:25:26

+0

您是对的。将编辑我的答案。 – steveoh 2012-03-07 09:27:07

+0

@steveoh:str_replace替换所有发生,但我只想要第一次出现,如果它在开始像ltrim函数一样存在,请仅删除第一个空格。 – Ben 2012-03-07 09:30:33

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

这将取代所有发生。 preg_replace('/ OR /','',$ str,1)替换第一次出现的'OR',但不仅仅是领先的出现 – Ben 2012-03-07 09:42:55

试试这个

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

它的作用是从开始选择任何内容,直到第一白色空间和replcementWord更换。在replcementWord之后注意一个空格。这是因为我们在搜索字符串

+0

我也不如regEx。你可以试试这个链接[所以你想学习正则表达式?](http://www.stedee.id.au/Learn_Regular_Expressions) – 2012-03-07 09:34:08

+0

对不起,但我无法正确格式化 – 2012-03-07 09:34:58

添加\s的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

+0

与preg_replace('/ search /','replace',$ str,1)相同。 – Ben 2012-03-07 10:05:10

+2

@Ben功能是相似的,但绝对不一样。如果您使用需要通过正则表达式转义的字符,则在使用preg_replace时会发生意外错误。 – Anther 2012-10-17 19:54:05

+0

@mishu整天浪费,然后我找到了你的答案,谢谢哥们。 – 2015-05-14 16:20:54

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

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

ltrim()删除给定列表中的所有字符,而不是字符序列。请更新您的答案。 – Calin 2013-08-22 09:35:53

我跑到这个问题,需要的解决方案,这是不是100%适合我,因为如果字符串像$str = "mine'this,该appostrophe会产生问题。所以我想出了一个痘痘绝招:

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