djames
djames

Reputation: 227

PHP - Regex replace everything not letter or space and everything after it

I'm trying to write a regex that replaces everything after something that's not a space or a letter in PHP.

I currently have the following

$_product[self::NAME] = preg_replace('^[a-z .*$]+$/i', '', $_product[self::NAME]);

It replaces the string with a blank string.

Here are some examples of what I'm replacing

Milk - 50 Gallons

should return

Milk

This string

chocolate milk - 50 gallons

should return

chocolate milk

It should do the same even if the hyphens are not there, meaning

Milk 50 gallons

should return

Milk

What is wrong in my regex?

Upvotes: 2

Views: 2006

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626903

The It replaces the string with a blank string proves you made a typo when posting the question, and you actually have '/^[a-z .*$]+$/i' regex.

That also means that your regex matches any string that contains one or more chars from the [a-z .*$] set (ASCII letters, space, dot, * or $ symbols).

If you need a regex that replaces everything after something that's not a space or a letter, you need

preg_replace('/\s*[^a-z\s].*$/i', '', $_product[self::NAME]);

See the regex demo

Details:

  • \s* - zero or more whitespaces
  • [^a-z\s] - any char other than ASCII letter or whitespace
  • .* - any zero or more characters other than newline (add /s modifier to also match newlines)
  • $ - end of string.

Upvotes: 1

Related Questions