Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace a nth occurrence in a string

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 provided value.

$subject = "SELECT uid FROM users WHERE uid = ? or username = ?";

So, i need function like str_replace_nth($seach, $replace, $subject, $nth) and for second question mark it should be called as str_replace_nth("?", $username, $subject, 2);

Any ideas?

P.S. Please, don't suggest me to use PDO, because I'm working on FDO (Facebook Data Object) a library with an interface similar to PDO, but for FQL.

Important notice! I've figured out that this approach is bad because after first replacement the query is modified and indexes are lost. (Bad approaches come when you're programming late at night :() So, as @GolezTrol mention in comment, it's better to replace all at once.

like image 897
sasa Avatar asked Nov 11 '13 13:11

sasa


1 Answers

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);
like image 150
bitWorking Avatar answered Oct 01 '22 21:10

bitWorking