Search code examples
phpstringtruncate

Remove remainder of string after first encountered non-alphanumeric character (keep all leading space-delimited "words")


How do I cut off the above strings at first non-alphanumeric character using a regular expression (ideally with no lingering trailing spaces after the truncation)?

The non-alphanumeric characters will not be known in advance but they might be a hyphen, a comma, an opening parenthesis, etc. I only want to keep the leading words prior to the symbol.

Input strings:

  • iPhone 7 plus - space grey (New)
  • iPhone6 plus, brand new, (Used)
  • iPhone 5 ( black)

Desired results:

  • iPhone 7 plus
  • iPhone6 plus
  • iPhone 5

Solution

  • If you don't need the second part, just match the first:

    preg_match('/[A-Z0-9\s]+/i', $string, $match);
    echo $match[0];
    

    Match letters A-Z, numbers 0-9 and spaces \s one or more times + case-insensitive i.