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

  • explode the string by / and do what ever you want .try this

    $hello="hey/mate/from/outside/nothing/is/to/be/done";
    $a=explode('/',$hello);// returns an array 
    echo $a[0]."/".$a[1];