首页 > 解决方案 > 替换字符串中的字符(连同存在于数组中的字符)

问题描述

我需要替换某些字符。

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

这样我可以替换用户名和电子邮件,我怎样才能使它成为站点、博客和滚动?

谢谢!

标签: phpstr-replace

解决方案


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

$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

演示: https ://ideone.com/isN90N


推荐阅读