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
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);