有需求就會去開發,如果沒有現成的可用的時候,有時候就是會想要只取代第一個出現的目標字串,下面的 PHP 程式碼可以滿足這個功能,你也可指定要取代的次數。
function str_replace_count ($search, $replace, $subject, $count = 1)
{
$search = '/'.preg_quote($search, '/').'/';
return preg_replace($search, $replace, $subject, $count);
}
// Test
$subject = "abc123456abc789654abc456abc123";
$search = "abc";
$replace = "xxyyzz";
echo "Replace once : ".str_replace_count($search, $replace, $subject)."\n";
echo "Replace twice: ".str_replace_count($search, $replace, $subject, 2)."\n";
下面是測試的結果:
Replace once : xxyyzz123456abc789654abc456abc123
Replace twice: xxyyzz123456xxyyzz789654abc456abc123