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.

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

报告相同问题?

悬赏问题

  • ¥60 pb数据库修改或者求完整pb库存系统,需为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
  • ¥15 求lingo代码和思路