Replace string only once with php preg_replace

You are looking for preg_quote instead of trying to escape the \ yourself (which doesn’t take [, + and many others into account):

$return = preg_replace("https://stackoverflow.com/".preg_quote($remove,"https://stackoverflow.com/")."https://stackoverflow.com/", $replace, $string, 1);

Leave a Comment