Reputation: 127
I got this variable
$test = 'Alpha, Gamma, Beta';
What is the best practice to get this result? How do I add a certain word in between such as I did below add Rays.
Alpha Rays, Gamma Rays, Beta Rays
Upvotes: 1
Views: 131
Reputation: 500
You can try using the str_replace function for every comma it finds.
Example:
$str = str_replace("," , " Rays," , $test.' Rays');
You can find more about it here
Upvotes: 1
Reputation: 77925
Try this code piece
$test = preg_replace('/(,|$)/', ' Rays$1', $test);
I can't tell if it is "Best practice", but it is a practice that works and is simple. You can probably make another solution which would give you better performance, and that might be "best practice" if performance is the issue.
But if simplicity is the way, this is good.
Edit:
Since some other answers are using str_replace
, I can give a working solution for that too:
$test = str_replace(',',' Rays,', $test).(empty($test)?'':' Rays');
Upvotes: 9