微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐