relo80
relo80

Reputation: 285

How to replace placeholder in string

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?

Upvotes: 0

Views: 946

Answers (2)

user3783243
user3783243

Reputation: 5223

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.

Upvotes: 1

relo80
relo80

Reputation: 285

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
    );

Upvotes: 0

Related Questions