php str_replace()与关联数组

yduiuuwa  于 2023-04-04  发布在  PHP
关注(0)|答案(5)|浏览(151)

你可以在str_replace()中使用数组:

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

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

但是如果你有关联数组呢?

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

如何将它与str_replace()一起使用?
速度很重要-阵列足够大。

1zmg4dgp

1zmg4dgp1#

$text = strtr($text, $array_from_to)
顺便说一下,这仍然是一个一维的“数组”。

cgvd09ve

cgvd09ve2#

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

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

to字段将忽略数组中的键。这里的键函数是array_keys

sulc1iza

sulc1iza3#

$text='yadav+RAHUL(from2';

  $array_from_to = array('+' => 'Z1',
                         '-' => 'Z2',
                         '&' => 'Z3',
                         '&&' => 'Z4',
                         '||' => 'Z5',
                         '!' => 'Z6',
                         '(' => 'Z7',
                         ')' => 'Z8',
                         '[' => 'Z9',
                         ']' => 'Zx1',
                         '^' => 'Zx2',
                         '"' => 'Zx3',
                         '*' => 'Zx4',
                         '~' => 'Zx5',
                         '?' => 'Zx6',
                         ':' => 'Zx7',
                         "'" => 'Zx8');

  $text = strtr($text,$array_from_to);

   echo $text;

 //output is

yadavZ1RAHULZ7from2
r8uurelv

r8uurelv4#

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

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

结果为Hello Qiao, welcome to stackoverflow.

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

这不是一个二维数组,它是一个关联数组。
扩展第一个示例,其中我们将$search作为数组的键,$replace作为它的值,代码如下所示。

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

结果为Hello Qiao, welcome to stackoverflow.

k5ifujac

k5ifujac5#

$keys = array_keys($array);
$values = array_values($array);
$text = str_replace($key, $values, $string);

相关问题