ilişkisel dizi ile str_replace ()

3 Cevap

Sen str_replace ile diziler kullanabilirsiniz ():

$array_from = array ('from1', 'from2'); 
$array_to = array ('to1', 'to2');

$text = str_replace ($array_from, $array_to, $text);

Ama ilişkisel dizi ne varsa?

$array_from_to = array (
 'from1' => 'to1';
 'from2' => 'to2';
);

How can you use it with str_replace()?
Speed matters - array is big enough.

3 Cevap

$text = strtr($text, $array_from_to)

Bu arada, hala, bir tek boyutlu bir "dizi" dir.

$array_from_to = array (
    'from1' => 'to1',
    'from2' => 'to2'
);

$text = str_replace(array_keys($array_from_to), $array_from_to, $text);

to alanı, dizideki anahtarları yok sayacaktır. Burada anahtar işlevi array_keys.

$search = array('{user}', '{site}');
$replace = array('Qiao', 'stackoverflow');
$subject = 'Hello {user}, welcome to {site}.';

echo str_replace ($search, $replace, $subject);

Sonuçlar Hello Qiao, welcome to stackoverflow..

$array_from_to = array (
    'from1' => 'to1';
    'from2' => 'to2';
);

Bu bir ilişkisel dizi var, iki boyutlu bir dizi değil.

Biz dizinin anahtarları olarak $ arama yerleştirin ve bu değerleri olduğu gibi $ yerine burada ilk örnekte genişletilmesi, kod böyle olmazdı.

$searchAndReplace = array(
    '{user}' => 'Qiao',
    '{site}' => 'stackoverflow'
);

$search = array_keys($searchAndReplace);
$replace = array_value($searchAndReplace);
# Our subject is the same as our first example.

echo str_replace ($search, $replace, $subject);

Sonuçlar Hello Qiao, welcome to stackoverflow..