Search code examples
phpstringsanitizationtruncation

Truncate string at second occurrence of a character


I want to get the part of a string which is just before the second forward slash. Let's say I have a string variable named $hello and it is:

$hello = "hey/mate/from/outside/nothing/is/to/be/done";

How to get the part of the string up to second slash so that it becomes:

$x = "hey/mate"

Yes, I can get part of string up to first slash (/) by:

$x = strtok($hello,  '/');

Is there any functions that I can use? Can we get part of string up to the second slash?


Solution

  • strtok keeps track of the string it breaks up, so you can use it as it describes in the docs

    $str = "hey/mate/from/outside/nothing/is/to/be/done";
    
    $first = strtok($str, "/");
    $second = strtok("/");
    
    echo "$first/$second"; // "hey/mate"