Solvision
Solvision

Reputation: 193

PHP preg_replace not working as expected

I'm trying to run a find replace of multiple values to do a mail merge effect on an HTML signature stored in the database.

I can get the string part replaced no worries, but for some reason it's leaving the "[" & "]" behind in the output.

Merge tags in the HTML would look like this: [FirstName], [LastName]

Original HTML would look like this:

Kind regards

[FirstName] [LastName]

After running the mailmerge function it should look like this:

Kind regards

John Smith

Here is what I've come up with so far, and Im sure the issue is something small:

public function merge_user_signature() {
    $user = $this->get_user_by_id();
    //spit_out($user);

    $authorisedMergeTags = array (
        "[FirstName]" => $user->firstName, 
        "[LastName]" => $user->lastName
    );

    $keys = array_keys($authorisedMergeTags);
    $values = array_values($authorisedMergeTags);
    $html = $this->get_user_signature();

    $mergedSignature = preg_replace($keys, array_values($authorisedMergeTags), $html);

    return $mergedSignature;
}

Thanks in advance

Upvotes: 0

Views: 84

Answers (1)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89557

You don't need to use a regex to deal with literal strings (whatever the situation):

return strtr($html, $authorisedMergeTags);

Upvotes: 1

Related Questions