PHP str_replace对于第一个实例是不同的

时间:2014-01-14 08:45:56

标签: php str-replace

我有以下str_replace代码:

$filterString = "[++] has performed well. [++] is showing good understanding";

echo str_replace("[++]", "Name", $filterString);

它基本上用{名称替换[++]的所有实例。但是,我只想用名称替换[++]的第一个实例,所有其他实例应该说他

知道我怎么能这样做吗?

由于

5 个答案:

答案 0 :(得分:2)

Using str_replace so that it only acts on the first match?

echo preg_replace('/\[\+\+\]/', 'Name', $filterString, 1);

答案 1 :(得分:0)

您可以使用preg_replace()代替str_replace()

mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )

在第一次替换之后,您可以使用str_replace()将所有其他++替换为“He”。

稍后编辑: 我查看了,我看到str_replace()有一个limit参数,因此您也可以使用它而不是preg_replace()

答案 2 :(得分:0)

只需投入一行解决方案:

$filterString = str_replace("[++]","He",preg_replace("/\[\+\+\]/", "Name", $filterString, 1));

------ ----- EDIT

$filterString = preg_replace_callback('/[.!?].*?\w/',
                              function($matches) { return strtoupper($matches[0]);},
                              str_replace("[++]","he",preg_replace("/\[\+\+\]/", "Name", $filterString, 1))); 

这会将所有以句号开头的字符更改为大写,并修复以前的所有问题。

答案 3 :(得分:0)

如果您只想将[++]替换为“Name”一次,则应使用limit参数使用preg_replace,然后您可以替换字符串的其余部分:

$filterString = "[++] has performed well. [++] is showing good understanding. [++] is a good student.";
$filterString = preg_replace("/\[\+\+\]/",'Name',$filterString,1);
$filterString = str_replace("[++]",'He',$filterString);     
echo $filterString; //will print "Name has performed well. He is showing good understanding. He is a good student."

答案 4 :(得分:0)

试试这个......

$filterString = "[++] has performed well. [++] is showing good understanding.";

$newstr = substr_replace($filterString, "Name", 0, 4);

echo str_replace("[++]", "He", $newstr);