1

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

1
  • Is the string always going to be of the form 'something{comma}{space}'... ? Commented Apr 10, 2012 at 13:07

3 Answers 3

9

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');
Sign up to request clarification or add additional context in comments.

2 Comments

in above code (last code line) It comes in this order 'Alpha Rays, Beta, Rays, Gamma Rays'. How to bring it this way ' Rays Alpha, Rays Beta, RAys Gamma' ?
@Mas: If you refer to the line using str_replace, you can place the word first this way: $test = (empty($test)?'':'Rays ').str_replace(',', ', Rays', $test);
1

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

Comments

0

use explode

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

then implode

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

or foreach and add something different. implode - explode

1 Comment

Beta won't get any 'Rays' using this solution I am afraid.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.