php - 替换字符串中的字符(连同存在于数组中的字符)
问题描述
我需要替换某些字符。
$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
推荐阅读
- spring-boot - 使用基于索引的运算符 <-> 进行 Postgis Spring Boot 集成测试
- react-native - 我正在使用带有加号按钮的底部选项卡,但是加号按钮在仅在 android 中反应原生的一半区域中不可点击?
- javascript - 如何从同一个对象中访问对象的属性?
- html - 如何上传没有html文件的网站
- python - 使用 Python 的请求查询数据返回状态码 512
- vue.js - 显示来自 API Vue.js 的随机对象
- java - 为什么这个视图不显示在模拟器中?
- r - 请教一个将中文数字混合字符串转换为英文数字字符串的解决方案
- javascript - 防止将包添加到 yarn.lock
- amazon-web-services - Vault UI 未在浏览器中打开