-2

I have a stored set of messages(string) for sending sms through PHP in MySql, say

We have received [MACHINE_NAME] for service. Your service request id is [NEW_SERVICE_ID]. Thank you.

Now I have to replace [MACHINE_NAME] with machine name and [NEW_SERVICE_ID] with service id generated by PHP script. Do I need to use str_replace() function multiple times to replace words?

user3045457
  • 164
  • 1
  • 3
  • 12
  • 1
    Does this answer your question? [How to replace multiple items from a text string in PHP?](https://stackoverflow.com/questions/9393885/how-to-replace-multiple-items-from-a-text-string-in-php) – ggorlen Jan 07 '20 at 19:33

2 Answers2

3

Do it like this

$str="We have received [MACHINE_NAME] for service. Your service request id is [NEW_SERVICE_ID]. Thank you.";
$remove = array("[MACHINE_NAME]", "[NEW_SERVICE_ID]");
$add = array("YOURMACHINE_NAME", "SERVICE_ID");
echo $onlyconsonants = str_replace($remove, $add,$str );
Sajitha Rathnayake
  • 1,688
  • 3
  • 26
  • 47
2

No, you don't have to: just use arrays both for search and replace params, as described in the docs:

$res = str_replace(
   ['[MACHINE_NAME]', '[NEW_SERVICE_ID]'],
   [ $machine_name, $new_service_id ],
   $source);
raina77ow
  • 103,633
  • 15
  • 192
  • 229