duanju8431 2018-06-06 06:16
浏览 46
已采纳

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

I need to replace certain characters.

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

Also, $key_value is an array which gives me array key and values like:

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

Using

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

This way I can replace username and email, How can I make it to site, blog and roll?

Thanks!

  • 写回答

3条回答 默认 最新

  • douyangquan2474 2018-06-06 06:27
    关注

    You can use the following solution:

    $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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 关于无人驾驶的航向角
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退