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 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失