duanmiyang6201 2017-04-10 16:34
浏览 25
已采纳

用多个源替换字符串中的多个值

I have a pixel like:

<img src='http://www.montag.com/directory_folder/tracking_noip.php?tracking=[ID_MTG]&data=[TEL]' height='1' width='1' border='0'/>

I need to replace the keys [TEL] and [ID_MTG] with the value I receive from a script. For example if I have:

$tel = "0613321223";
$id_mtg = "4875";
$email = "thatmail@gmail.com";

I need to output:

<img src='http://www.montag.com/directory_folder/tracking_noip.php?tracking=4875&data=0613321223' height='1' width='1' border='0'/>

If I have:

<img src='http://www.montag.com/directory_folder/tracking_noip.php?tracking=[ID_MTG]&data=[EMAIL]' height='1' width='1' border='0'/>

I need to ouput:

<img src='http://www.montag.com/directory_folder/tracking_noip.php?tracking=4875&data=thatmail@gmail.com' height='1' width='1' border='0'/>

I have:

$tel = "0613357221";
$email = "Chachachou@gmail.com";
$id_mtg = "560";

$string = "<img src='http://www.montag.com/directory_folder/tracking_noip.php?tracking=[TEL]&data=[ID_MTG]' height='1' width='1' border='0'/>";
$patterns = array();
$patterns[0] = ' /\[TEL\]/ ';
$patterns[1] = ' /\[EMAIL\]/ ';
$patterns[2] = ' /\[ID_MTG\]/ ';
$replacements = array();
$replacements[2] = $id_mtg;
$replacements[1] = $email;
$replacements[0] = $tel;
echo htmlentities(preg_replace($patterns, $replacements, $string));

But my string is:

<img src='http://www.montag.com/directory_folder/tracking_noip.php?tracking=520&data=0613357221' height='1' width='1' border='0'/>

The order is reversed.

  • 写回答

2条回答 默认 最新

  • douqianni4080 2017-04-10 16:51
    关注

    The order is wrong because you defined your $replacements in reverse order. Even though you specified indexes in descending order, the order in which you created the array is preserved. Check this with print_r($replacements);. You could sort by keys with ksort() if needed to get the array in the proper order.

    But for this application, strtr() or str_replace() makes more sense. Make sure to define the arrays in the same order:

    $search  = array('[TEL]', '[EMAIL]', '[ID_MTG]');
    $replace = array($tel, $email, $id_mtg);
    
    $result = str_replace($search, $replace, $string);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab