如何用给定的数组替换多个模式?

How to replace multiple patterns with given array?

我有像

这样的字符串
$text = "Hello :name its your :num_visit";

和数组

 $attr = [ ":name" => "Danny", ":num_visit" => 6];

我想用数组中的给定值替换 $text 的模式,例如 :name, :num_visit(数组具有相同的键名)。

php可以吗?

使用str_replace() 替换那些。将 keys 传递给 search,将 values 传递给 replace -

$text = "Hello :name its your :num_visit";
$attr = [ ":name" => "Danny", ":num_visit" => 6];

echo str_replace(array_keys($attr), $attr, $text);

输出

Hello Danny its your 6

str_replace()

Working code

只需使用 strtr() 并将 search/replacement 数组作为第二个参数传递,例如

<?php

    $text = "Hello :name its your :num_visit";
    $attr = [":name" => "Danny", ":num_visit" => 6];
    echo strtr($text, $attr);

?>

输出:

Hello Danny its your 6

您可以使用 str_replace().

$text = "Hello :name its your :num_visit";
str_replace( array(':name',':num_visit'), array('Danny','6'), $text );

:name 将替换为 Danny:num_visit 将替换为 6