How to replace a nth occurrence in a string

前端 未结 4 710
盖世英雄少女心
盖世英雄少女心 2020-12-19 04:28

I need a simple and fast solution to replace nth occurrence (placeholder) in a string.

For example, nth question mark in sql query should be replaced with a provide

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-19 04:41

    Instead of using question marks, why don't use markers like that :

    $subject = "SELECT uid FROM users WHERE uid = :uid or username = :username";
    $parameters = array(
        ':uid' => 42,
        ':username' => 'John',
    );
    $subject = str_replace(array_keys($parameters), $parameters, $subject);
    

提交回复
热议问题