PHP强制str_replace只替换一个结果

参见英文答案 > Using str_replace so that it only acts on the first match?                                    22个
这完美地运作:

$replaceLyrics=str_replace
(
    'story',
    '_____',
    'The story of my life I take her home I drive all night to keep her warm and time Is frozen (the story of, the story of)'
);

echo $replaceLyrics;

输出

The _____ of my life I take her home I drive all night to keep her warm and time Is frozen (the _____ of, the _____ of)

我的问题是,是否可以使用内部PHP功能仅替换匹配中的第一个匹配而不是全部替换.

我期待得到这个输出

The _____ of my life I take her home I drive all night to keep her warm and time Is frozen (the story of, the story of)

解决方法:

这可以使用preg_replace来完成.

<?
$str = 'story story story';
echo preg_replace('/story/', '___', $str, 1);

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...