phpsubstring

How to isolate the characters in a string occurring before the first space?


I'm just wondering if there a way to write this code in just one line.

$exp = explode(" ", $text);
$cut = $exp[0];

So without having to assign variables.


Solution

  • If you only ever want the first part, then avoid the array workaround with strtok:

    $cut = strtok($text, " ");
    

    It cuts out something from the string until the first delimiter (space in your case).