【问题标题】:PHP force str_replace to replace only one of results [duplicate]PHP强制str_replace仅替换结果之一[重复]
【发布时间】:2015-03-22 08:32:27
【问题描述】:

这是完美的工作:

$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_match 函数和 preg_replace。

标签: php arrays string foreach str-replace


【解决方案1】:

这可以使用 preg_replace 来完成。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-29
    • 1970-01-01
    • 2012-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-21
    • 2016-01-11
    相关资源
    最近更新 更多