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 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 虚心请教几个问题,小生先有礼了
  • ¥30 截图中的mathematics程序转换成matlab