Mas
Mas

Reputation: 127

PHP variable, adding a word in between

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

Answers (3)

Stefan Manciu
Stefan Manciu

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

ANisus
ANisus

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

Millard
Millard

Reputation: 1157

use explode

$x = explode(",", $test);

then implode

$x = implode(" Ray ,", $x);

or foreach and add something different. implode - explode

Upvotes: 0

Related Questions