替换字符串中的字符(以及数组中存在的字符)

Replace characters in a string ( along with which exists in array )

我需要替换某些字符。

$to_replace = array( "{username}", "{email}" );
$replace_with = array( $username, $email );

此外,$key_value 是一个数组,它为我提供数组键和值,例如:

array(
  'site' => 'abc.com',
  'blog' => 'blog.com'
  'roll' => 42
);

正在使用

$message = 'This is a {username} speaking, my email is {email}, and my site is {site} with roll {roll}';

$message = str_replace( $to_replace, $replace_with, $message );

这样我可以替换用户名和电子邮件,我怎样才能进入网站、博客和滚动?

谢谢!

您可以使用以下解决方案:

$email = 'johndoe@example.com';
$username = 'johndoe';

$to_replace = array( "{username}", "{email}" );
$replace_with = array( $username, $email );

$key_value = array(
    'site' => 'abc.com',
    'blog' => 'blog.com',
    'roll' => 42
);

//add the keys and values from $key_value to the replacement arrays.
$to_replace = array_merge($to_replace, array_keys($key_value));
$replace_with = array_merge($replace_with, array_values($key_value));

//surround every key with { and }.
array_walk($to_replace, function(&$value, $key) { $value = '{'.trim($value, '{}').'}';});

$message = 'This is a {username} speaking, my email is {email}, and my site is {site} with roll {roll}';
$message = str_replace( $to_replace, $replace_with, $message );

var_dump($message); //This is a johndoe speaking, my email is johndoe@example.com, and my site is abc.com with roll 42

demo: https://ideone.com/isN90N

只用您要替换的所有数据填充前两个数组会容易得多,但如果您坚持使用目前已有的数据,那么这将完成工作。

这会获取最后一个数组的键(使用 array_keys())并使用 array_walk() 在其周围添加 {}。数组值并将它们合并到原始数组中。

$to_replace = array( "{username}", "{email}" );
$replace_with = array( $username, $email );

$extra = array(
    'site' => 'abc.com',
    'blog' => 'blog.com',
  'roll' => 42
);

$extraTo = array_keys($extra);
array_walk($extraTo, function(&$d) { $d= "{".$d."}";});
$to_replace = array_merge($to_replace, $extraTo);
$replace_with = array_merge($replace_with, array_values($extra));

$message = 'This is a {username} speaking, my email is {email}, and my site is {site} with roll {roll}';
$message = str_replace( $to_replace, $replace_with, $message );

echo $message;

您可以使用 extract 函数以最简单的方式实现此目的。

并且,尝试将消息逻辑包装在一个单独的函数中,以清理数据并避免变量名称冲突。

function createMessage($username, $email, $userMeta) {
    extract($userMeta);
    return "This is a {$username} speaking, my email is {$email}, and my site is {$site} with roll {$roll}";
}

$username = 'awesome';
$email = 'email@email.com';
$userMeta = array(
    'site' => 'abc.com',
    'blog' => 'blog.com',
    'roll' => 42
);

echo createMessage($username, $email, $userMeta);
// This is a awesome speaking, my email is email@email.com, and my site is abc.com with roll 42

警告:不要对不受信任的数据使用 extract(),例如用户输入(例如 $_GET、$_FILES)。