Search code examples
phpstringsubstrstrstr

Cut certain part of string after a specific character


I am trying to basically cut a certain part of string after a specific character and then print it. I have this string and I need to cut the part after the last "/". Which means from this string:

$mystring = "https://example.com/node/some-article/diskuse828000";

I need to cut the part after the last "/" character, so it would return string looking like this:

$newstring = "https://example.com/node/some-article/

I have tried functions like substr and strstr, but I dont know how to cut the string after the specific last "/".


Solution

  • You can use a function meant for paths:

    $newstring = dirname($mystring);
    

    Or you can find the position of the last / and extract up to it:

    $newstring = substr($mystring, 0, strrpos($mystring, '/'));