How to replace a nth occurrence in a string

前端 未结 4 712
盖世英雄少女心
盖世英雄少女心 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条回答
  •  清歌不尽
    2020-12-19 04:45

    Here is the function you asked for:

    $subject = "SELECT uid FROM users WHERE uid = ? or username = ?";
    
    function str_replace_nth($search, $replace, $subject, $nth)
    {
        $found = preg_match_all('/'.preg_quote($search).'/', $subject, $matches, PREG_OFFSET_CAPTURE);
        if (false !== $found && $found > $nth) {
            return substr_replace($subject, $replace, $matches[0][$nth][1], strlen($search));
        }
        return $subject;
    }
    
    echo str_replace_nth('?', 'username', $subject, 1);
    

    Note: $nth is a zero based index!

    But I'll recommend to use something like the following to replace the placeholders:

    $subject = "SELECT uid FROM users WHERE uid = ? or username = ?";
    
    $args = array('1', 'steve');
    echo vsprintf(str_replace('?', '%s', $subject), $args);
    

提交回复
热议问题