PHP替换字符串的第一次出现,从第0位
我想搜索和PHP中的另一个替换的第一个字就像如下:PHP替换字符串的第一次出现,从第0位
$str="nothing inside";
通过搜索替换“什么”到“东西”,并且不使用替代substr
输出应该是:“里面的东西”
使用preg_replace()
为1的限制:
preg_replace('/nothing/', 'something', $str, 1);
更换正则表达式/nothing/
您要搜索的任何字符串。由于正则表达式总是从左到右进行计算,因此它将始终与第一个实例匹配。
如果您只是使用通用字符串,则此解决方案存在转义问题,例如$和$等字符串在该字符串中。 http://stackoverflow.com/questions/1252693/php-str-replace-that-only-acts-on-the-first-match有一个更通用的解决方案。 – Anther 2012-10-17 18:55:37
preg_replace('/nothing/', 'something', $str, 1);
这将取代所有发生。 preg_replace('/ OR /','',$ str,1)替换第一次出现的'OR',但不仅仅是领先的出现 – Ben 2012-03-07 09:42:55
试试这个
preg_replace('/^[a-zA-Z]\s/', 'ReplacementWord ', $string)
它的作用是从开始选择任何内容,直到第一白色空间和replcementWord更换。在replcementWord之后注意一个空格。这是因为我们在搜索字符串
我也不如regEx。你可以试试这个链接[所以你想学习正则表达式?](http://www.stedee.id.au/Learn_Regular_Expressions) – 2012-03-07 09:34:08
对不起,但我无法正确格式化 – 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;
}
ltrim()将删除字符串开头的不需要的文本。
$do = 'nothing'; // what you want
$dont = 'something'; // what you dont want
$str = 'something inside';
$newstr = $do.ltrim($str , $dont);
echo $newstr.'<br>';
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));
}
为什么没有substr? – lfxgroove 2012-03-07 09:27:37
[使用str \ _replace以便它只对第一个匹配起作用]的可能的重复?(http://stackoverflow.com/questions/1252693/using-str-replace-so-that-it-only-acts-on - 第一次匹配) – Bas 2015-04-24 14:08:25