doukan4039 2016-01-16 06:06
浏览 15
已采纳

在PHP中向str_replace添加字符

I have a php file with thread ($tid) and post ($pid) ids defined and I'm looking to use str_replace to combine them and create my desired output (below) with &p= added:

Desired output:

$tid&p=$pid

The closest I've got is doing this:

$tid=$t1;
$pid=$p1;
$tid=str_replace("$tid","$tid"."$pid",$tid);

The result is:

$tid$pid

I may need to use a function (not sure which if so?) in the str_replace to support the &p= being added, as trying to add it in the quotes directly doesn't seem to work resulting only in database errors.

Edit #1: I tried doing the following based on the comments thus far:

$tid="";
$tid.="$t1";
$tid.="$p1"; 
$tid=$tid;

That results in the same as my previous example above:

$tid$pid

As soon as I add another with the &p= I get a database error:

$tid.="&p=";

So my question now is how to add the &p= to my Edit #1 example above correctly?

  • 写回答

1条回答 默认 最新

  • dscw1223 2016-01-16 07:57
    关注

    I'm attempting to understand the question a little bit. You have a couple options that are alluded to in the comments above. You could, for instance (where '1', '2', and '3' are replaced by the desired values):

    <?php
    $tid=1;
    $pid=2;
    $amp=3;
    $tid=str_replace("$tid","$tid".'$amp;p='."$pid",$tid);
    
    echo $tid;
    ?>
    

    Here you can just explicitly state in the 'replace' argument of str_replace that the missing string should be part of the replacement string.

    or you could also simply use the a concatenation operator to generate the string you desire which is probably simpler given what (little) I know of the surrounding code/use-case:

    <?php
    $tid=1;
    $pid=2;
    $amp=3;
    
    echo "$tid".'$amp;p='."$pid";
    ?>
    

    The reason I'd recommend the latter, is due to the fact that it's less resource intensive to actually produce the desired result which appears to just be a string. str_replace() searches the "haystack" or subject string using the search string and then must replace each of the found instances with the replace string.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题