1

Im trying to run a str_replace on a 'dynamic string' coming from a user.

But everytime my function is run, it seems to output the wrong thing and i can't figure out how to fix it.

So for instance, if $payload['Name'] = 'this name'

Then when the function returns the string turns into

this name Placethis name

What seems to be happening is that its also replacing the Name inside the PlaceName in the array.

My code is as follows;

function formatThis($payload)
{
    $description = '';
    if ( array_key_exists('Description', $payload) ) {
        $description = $payload['Description'];
    }

    $placeName = '';
    if ( array_key_exists('PlaceName', $payload) ) {
        $placeName = $payload['PlaceName'];
    }

    $dynamicString = "Name PlaceName"
    $template = str_replace(
        array("Name", "Description", "PlaceName"),
        array($payload['Name'], $description, $placeName),
        $dynamicString
    );

    return $template;
}
1
  • It seems that the string actually replaces correctly to the description of the function. Its just not the behavior you like. Commented Sep 16, 2019 at 4:13

1 Answer 1

1

Instead of useing str_replace, you should use `preg_replace', check the Demo

preg_replace(['/\bName\b/','/\bDescription\b/','/\bPlaceName\b/'], [$payload['Name'], $description, $placeName], $dynamicString);
Sign up to request clarification or add additional context in comments.

1 Comment

While this might work, the problem at hand is a good example were placeholders usually have a special syntax like {here} or {%here%}

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.