0

I want to replace placeholder into a given string by using PHP (no JavaScript).

For that I have a list of possible placeholders and the new string for each:

$placeholder=array( 'firstplaceholder'=>'new text for ph1',
'2ndplaceholder'=>'new text for ph2',
'3placeholder'=>'new text for ph3',
'4placeholder'=>'new text for ph4'
...

And the string with the placeholders

$string='This is my text, here I want to use {2ndplaceholder}";

Normally I will do it in this way:

foreach($placeholder as $k=>$e)
{
if(strpos ( $string , $k){ $string=str_replace('{'.$k.'}',$e,$string);
}

Now I think about runtime. If I have a big list of placeholders it makes more sense to check if I have placeholders in the string and replace them instead loop each placeholder if I only need few of them.

How can I make it or how can I create a array from the string which has all placeholders from the string, to loop only them?

2
  • strtr is an alternative that does the same job. Commented Feb 1, 2021 at 16:23
  • And also, don't worry about passing exactly those placeholders present in the string. If you pass something extra, it simply won't replace anything. Commented Feb 1, 2021 at 16:24

2 Answers 2

1

The simplest solution would be using the keys and values in the str_replace but you need the curly braces on the placeholders so they match.

$placeholder=array( '{firstplaceholder}'=>'new text for ph1',
'{2ndplaceholder}'=>'new text for ph2',
'{3placeholder}'=>'new text for ph3',
'{4placeholder}'=>'new text for ph4');
echo str_replace(array_keys($placeholder), $placeholder, 'This is my text, here I want to use {2ndplaceholder}');

or

$placeholder=array( '{firstplaceholder}'=>'new text for ph1',
'{2ndplaceholder}'=>'new text for ph2',
'{3placeholder}'=>'new text for ph3',
'{4placeholder}'=>'new text for ph4');
echo str_replace(array_keys($placeholder), array_values($placeholder), 'This is my text, here I want to use {2ndplaceholder}');

if array_values function is easier to read. The str_replace uses the values natively so it isn't needed.

Sign up to request clarification or add additional context in comments.

Comments

0

now i find a faster way to solve this job

$newstring=preg_replace_callback('/{([A-Z0-9_]+)}/',
        function( $matches ) use ( $placeholders )
        {
            $key = strtolower( $matches[ 1 ] );
            return array_key_exists( $key, $placeholders ) ? $placeholders[ $key ] : $matches[ 0 ];        
        },            
        $string
    );

1 Comment

Simpler regex would be \w in place of [A-Z0-9_], they are the same...unless case matters but this would fail in that case anyways

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.