有人知道一种非常快速的方法来替换字符串中最后一个出现的字符串为另一个字符串吗?
请注意,该字符串的最后一个出现可能不是字符串的最后字符。
示例:
$search = 'The';
$replace = 'A';
$subject = 'The Quick Brown Fox Jumps Over The Lazy Dog';
预期输出:
The Quick Brown Fox Jumps Over A Lazy Dog
有人知道一种非常快速的方法来替换字符串中最后一个出现的字符串为另一个字符串吗?
请注意,该字符串的最后一个出现可能不是字符串的最后字符。
示例:
$search = 'The';
$replace = 'A';
$subject = 'The Quick Brown Fox Jumps Over The Lazy Dog';
预期输出:
The Quick Brown Fox Jumps Over A Lazy Dog
function str_lreplace($search, $replace, $subject)
{
$pos = strrpos($subject, $search);
if($pos !== false)
{
$subject = substr_replace($subject, $replace, $pos, strlen($search));
}
return $subject;
}
strpos - 在字符串中查找子字符串的第一个出现位置
- 编辑:哇。Php天才们真的创造了一个名为strpos
和strrpos
的函数吗?谢谢... - BarryBones41strstr
,strrstr
(https://linux.die.net/man/3/strrstr),这两个函数实际上是相同的功能。(但是他们一定要改名吗?) - alexis另一个一行代码,但没有使用 preg 函数:
$subject = 'bourbon, scotch, beer';
$search = ',';
$replace = ', and';
echo strrev(implode(strrev($replace), explode(strrev($search), strrev($subject), 2))); //output: bourbon, scotch, and beer
$string = 'this is my world, not my world';
$find = 'world';
$replace = 'farm';
$result = preg_replace(strrev("/$find/"),strrev($replace),strrev($string),1);
echo strrev($result); //output: this is my world, not my farm
last 'fox'
替换为'dog'
。$string = 'The quick brown fox, fox, fox jumps over the lazy fox!!!';
echo preg_replace('/(fox(?!.*fox))/', 'dog', $string);
输出:
The quick brown fox, fox, fox jumps over the lazy dog!!!
你可以这样做:
$str = 'Hello world';
$str = rtrim($str, 'world') . 'John';
结果是 'Hello John';
rtrim
的行为与你想象的不同。它会从字符串末尾删除任何按照搜索字符串中出现的字符(并始终附加替换字符串),例如:"Hello word" -> "Hello John","Hello lord" -> "Hello John","Hello motor" -> "Hello motJohn","Hello worldy" -> "Hello worldyJohn"。 - Jakertrim($str, 'dlorw')
是一样的。 - mickmackusa.*
即可。以下是做法示例:$text = "The quick brown fox, fox, fox, fox, jumps over etc.";
$fixed = preg_replace("((.*)fox)", "$1DUCK", $text);
print($fixed);
The quick brown fox, fox, fox, DUCK, jumps over etc.
\K
字符在这里。 - mickmackusafunction str_lreplace($search, $replace, $subject)
{
return preg_replace('~(.*)' . preg_quote($search, '~') . '(.*?)~', '$1' . $replace . '$2', $subject, 1);
}
更新 稍微更简洁的版本 (http://ideone.com/B8i4o):
function str_lreplace($search, $replace, $subject)
{
return preg_replace('~(.*)' . preg_quote($search, '~') . '~', '$1' . $replace, $subject, 1);
}
$string = "picture_0007_value";
$findChar =strrpos($string,"_");
if($findChar !== FALSE) {
$string[$findChar]=".";
}
echo $string;
除了代码中的错误,Faruk Unal 给出了最好的答案。一个函数就能解决问题。
您可以使用strrpos()函数来查找最后一个匹配项。
$string = "picture_0007_value";
$findChar =strrpos($string,"_");
$string[$findChar]=".";
echo $string;
输出:picture_0007.value
function str_lreplace($search, $replace, $subject){
return is_numeric($pos=strrpos($subject,$search))?
substr_replace($subject,$replace,$pos,strlen($search)):$subject;
}
s($str)->replaceLast($search, $replace)
有所帮助,这在此独立库中可以找到。 - caw