0

I am trying to replace some characters in a text block. All of the replacements are working except the one at the beginning of the string variable.

The text block contains: [FIRST_NAME] [LAST_NAME], This message is to inform you that...

The variables are defined as:

$fname = "John";
$lname = "Doe";

$messagebody = str_replace('[FIRST_NAME]',$fname,$messagebody);
$messagebody = str_replace('[LAST_NAME]',$lname,$messagebody);

The result I get is: [FIRST_NAME] Doe, This message is to inform you that...

Regardless of which tag I put first or how the syntax is {TAG} $$TAG or [TAG], the first one never gets replaced.

Can anyone tell me why and how to fix this? Thanks

peinearydevelopment
  • 11,042
  • 5
  • 48
  • 76
Andrew
  • 63
  • 1
  • 6
  • I don't see any problem with your code. I just tested. Can you paste your `$messagebody` variable? I want to see how you defined it, and what it contains. – Maihan Nijat Jan 29 '18 at 20:35
  • If `$messagebody = '[FIRST_NAME] [LAST_NAME]';`, the code works for me. – Anthony Jan 29 '18 at 20:36
  • $messagebody comes from an sql table with a field called message_body which is defined as a type text. – Andrew Jan 29 '18 at 21:12
  • If I put something in front of the string it works. Strange. $messagebody = 'START:'.$messagebody; – Andrew Jan 29 '18 at 21:20

1 Answers1

0

Until someone can provide me with an explanation for why this is happening, the workaround is to put a string in front and then remove it afterward:

$messagebody = 'START:'.$messagebody;

do what you need to do

$messagebody = substr($messagebody,6);

I believe it must have something to do with the fact that a string starts at position 0 and that maybe the str_replace function starts to look at position 1.

Maihan Nijat
  • 9,054
  • 11
  • 62
  • 110
Andrew
  • 63
  • 1
  • 6