Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Gabotronix's avatar

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:

"http://www.google.es/url?q=https://www.facebook.com/lacamperiamlg/&sa=U&ved=2ahUKEwjFkKOrxeHrAhXFFogKHa5nAI8QgU96BAgMEAQ&usg=AOvVaw2opxQ32h4Yg5LdpJLYjS6J"

Where there are two instances of "http", I would remove all characters prior to the last instance of "http", I'd have the following result:

https://www.facebook.com/lacamperiamlg/&sa=U&ved=2ahUKEwjFkKOrxeHrAhXFFogKHa5nAI8QgU96BAgMEAQ&usg=AOvVaw2opxQ32h4Yg5LdpJLYjS6J"

How can I do this with PHP?

0 likes
3 replies
ismaile's avatar

Edited

I would create a function like this one:

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's avatar

@ismaile what about content http in

httpUKEwjFkKOrxeHrAhXFFogKHa5nAI8QgU96BAgMEAQ&usg=AOvVaw2opxQ32h4Yg5LdpJLYjS6J
ismaile's avatar

@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.

Please or to participate in this conversation.