phpstringdelimitertext-extractionsentence

Get first word from a string -- which may be followed by a space or a punctuation mark


I found this solution on Stack Overflow for getting the first word from a sentence.

$myvalue = 'Test me more';
$arr = explode(' ',trim($myvalue));
echo $arr[0]; // will print Test

This is suitable when a space character is used to divide words. Does anyone know how to get the first word from a string if you do not know what the divider is? It can be ' ' (space), '.' (full stop), '.' (or comma).

Basically, how do you take anything that is a letter from a string up to the point where there is no letter?

E.g.:


Solution

  • preg_split is what you're looking for.

    $str = "bla1 bla2,bla3";
    $words = preg_split("/[\s,]+/", $str);
    

    This snippet splits the $str by space, \t, comma, \n.