Search code examples
phpstringtext-extraction

Get substring before first non-letter


How can I get a portion of the string from the beginning until the first non-alphabetic character?

Example strings:

  • Hello World
  • Hello&World
  • Hello5World

I'd like to get "Hello" from each of the above input strings.


Solution

  • You need to use the preg_split feature.

    $str = 'Hello&World';
    $words = preg_split('/[^\w]/',$str);
    
    echo $words[0];
    

    You can access Hello by $words[0], and World by $words[1]