简体   繁体   中英

PHP str_replace different for first instance

I've got the following str_replace code:

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

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

It basically replaces all instances of [++] with Name. However, i would like to only replace the first instance of the [++] with Name and all other instances should say He

Any idea how i can do this?

Thanks

使用str_replace使它只对第一个匹配起作用?

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

You can use preg_replace() instead of str_replace()

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

After this first replace, you can use str_replace() for all the other ++ to replace with "He".

Later edit: I checked and I saw that str_replace() has a limit parameter so you could use it too instead of preg_replace() .

Just to toss in a one-row solution:

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

This will change all characters that start a sentence to uppercase, plus fix all your earlier issues.

If you just want to replace [++] for "Name" once, you should use preg_replace using the limit parameter, and then you can replace the rest of the string:

$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."

Try this...

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM