PHP: Check for last instance of substring inside string and remove all characters before
Hi everybody, I want to check for each instance of substring "http" inside a string, and for the last instance of it I want to remove all characters before it excluding the substring, so for example for the given string:
function lastAndBeyond($subject, $search)
{
if ($search === '') {
return $subject;
}
$position = strrpos($subject, (string) $search);
if ($position === false) {
return $subject;
}
return substr($subject, $position);
}
And use it like this:
lastAndBeyond($mystring, 'http');
You can maybe find a nicer name :) and adapt the function if needed. In this case, if the search term is empty or if it is not found, it would return the initial string.
Hope this helps.
PS: I'd look for http:// or https:// to be more precise
@newbie360 You are right, I've actually mentioned this in my initial answer but I edited it to make it simpler. Indeed, to do it properly, I'd look for http:// and https://. I've put it back once again in the answer.