简体   繁体   中英

Replacing string with variables stored in an array

OK so i'm unsure with my syntax on this one, I do think the logic is self explanatory but I'm unsure if preg_replace will work or whether a loop is needed to get an end result.

$string = $randomizer->fecthRandomPhrase($cfg['seo']['meta']['descriptions']['single'], 3, $_SERVER['REQUEST_URI']);

Returns a string like this

Lorem ipsum dolor sit amet,[address1], [address2], [postcode]. consectetur adipiscing elit. Mauris id dui sem, eget laoreet tellus. Vivamus lacinia vestibulum odio a lobortis - [region]

I then search the string for the parts I want to change;

$find = array('[address1]','[address2]','[postcode]','[region]');

I then pull information stored in these variables and place them in an array;

$replace = array($ADDRESS1,$ADDRESS2,$POSTCODE,$region);

The before returning the phrase I apply a preg_replace to swap over the info I have stored

$phrase = preg_replace($find,$replace,$string);

Do I need to loop through the array $replace to allow the reading of each variable and for the replace to work or am I using the wrong function entirely?

str_replace() can take arrays as its first two parameters, you might want to consider that instead. Otherwise, you'd need to form a proper regex for $find in order to only invoke preg_replace() once, which you currently are not doing.

Usage:

$phrase = str_replace( $find, $replace, $string);

Now $phrase shoud contain your desired output.

use PHP's str_replace function like this

str_replace(array($your_replacement_array), array($your_replace_array), $string);

Hence what you want is this

str_replace(array('[address1]','[address2]','[postcode]',['region']), array($ADDRESS1,$ADDRESS2,$POSTCODE,$region), $string);

strtr is also useful.

On the following situation, only strtr works exptectedly.

$text = 'SonyEricsson is based in British, but Sony is based in Japan';

str_replace

code:

$search  = array(
    'SonyEricsson',
    'Sony',
);
$replace = array(
    '<a href="http://www.SonyEricsson.com">SonyEricsson</a>',
    '<a href="http://www.Sony.com">Sony</a>',
);
echo str_replace($search,$replace,$text);

result:

<a href="http://www.<a href="http://www.Sony.com">Sony</a>Ericsson.com"><a href="http://www.Sony.com">Sony</a>Ericsson</a> is based in British, but <a href="http://www.Sony.com">Sony</a> is based in Japan

strtr

code:

$replace_pairs = array(
    'SonyEricsson' => '<a href="http://www.SonyEricsson.com">SonyEricsson</a>',
    'Sony'         => '<a href="http://www.Sony.com">Sony</a>',
);
echo strtr($text,$replace_pairs);

result:

<a href="http://www.SonyeEricsson.com">SonyEricsson</a> is based in British, but <a href="http://www.Sony.com">Sony</a> is based in Japan

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM