duai1683 2010-12-31 23:05
浏览 181
已采纳

使用str_replace替换变量字符

Basically I am trying to do an str_replace with "?cat=(insert number here)"

$queryString2 = str_replace("cat=(insert number here)", "cat=4", $queryString);

Is there a way this can be accomplished? Str_replace + one character because the value im searching for could be anything.

?cat=7
?cat=3
?cat=4

Any suggestions?

  • 写回答

2条回答 默认 最新

  • doufei7464 2010-12-31 23:12
    关注

    A more reliable way of handling query strings would be to actually parse them.

    // If your original query string was just the data in $_GET, clone $_GET:
    $new_query = $_GET;
    // Otherwise, parse the original query string using parse_str:
    parse_str($original_query_string, $new_query);
    // Then, set the new cat value, and build a new query string.
    $new_query['cat'] = 4;
    $new_query_string = http_build_query($new_query);
    

    The technique you originally describe is the job of a regular expression :)

    $queryString2 = preg_replace('/cat=[0-9]+/', 'cat=4', $queryString);
    

    The regular expression cat=[0-9]+ matches the string cat= followed by one or more (+) digits ([0-9]). preg_replace replaces all matches of the regular expression (argument 1) found in the original string (argument 3) with the replacement string (argument 2) and returns the result.

    Note that this will also replace dog_and_cat=1 with dog_and_cat=4. borkweb's answer is a more complex regex, but handles that edge case if it could arise (e.g. this is a query string provided by the user).

    I prefer the actual query parsing, but the regular expression solution should ideally work just as well, assuming no edge cases.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示