0

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

M Khalid Junaid
  • 63,861
  • 10
  • 90
  • 118
John Smith
  • 449
  • 5
  • 8
  • 16

5 Answers5

2

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

echo preg_replace('/\[\+\+\]/', 'Name', $filterString, 1);
Community
  • 1
  • 1
Sergei Gorjunov
  • 1,789
  • 1
  • 14
  • 22
0

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().

tzortzik
  • 4,993
  • 9
  • 57
  • 88
0

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.

NewInTheBusiness
  • 1,465
  • 1
  • 9
  • 14
0

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."
dcapilla
  • 171
  • 6
0

Try this...

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

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

echo str_replace("[++]", "He", $newstr);
Deepu Sasidharan
  • 5,193
  • 10
  • 40
  • 97