Search and replace multiple keywords in a text block

I have this block of text that needs to be customizable in that some of the words / keywords that can be customized. Let's say this is the block of text below.

Dear [Name], Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat on [Date]. Ut wisi enim ad minim veniam, quis nostrud exercise ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo ensat. Please contact [PhoneNumber]

Words in square brackets are keywords that should be replaced. The data to replace them will be obtained from db, and this is normal. I want to know that this is the best way to do this. Should I just search for specific keywords one at a time (there are many other keywords, but there is no guarantee which one can be indicated in which block of text, so I will need to check all possible keywords for each block of text), and then replace them with the appropriate value using str_replace? Or is there a better way to do this? Thanks.

+4
source share
2 answers

str_replace can replace an entire array in one step:

$map = array('[PhoneNumber]'=>'...', '[Date]'=>'...',...);


$result = str_replace(array_keys($map), array_values($map), $input);
+5
source
$admin_email_text = 'This is [first-field-label] the test, you can send the email at [form-email]';
        $admin_email_text = str_replace("[form-email]", $biz_field_email, $admin_email_text);
        $admin_email_text = str_replace("[first-field-label]", $biz_field_one, $admin_email_text);
        print $admin_email_text;
0

All Articles