You might be overthinking it. While the substr() method will work perfectly it might be simpler to use rtrim() to remove any trailing slashes and then add one on.
$path = rtrim($path, "https://stackoverflow.com/") . "https://stackoverflow.com/";
Caution: this will trim multiple trailing forward slashes. so .////// becomes ./