2

I have the following operation which splits a string whenever it encounters an alphabet:

$splitOriginal = preg_split("/[a-zA-Z]/", implode('', array_slice($array, $key)), 2);

I want to extend it in such a way that it splits the string whenever the variable encountered is NOT a number, bracket, plus sign, hyphen, newline or tab.

I have written a regex which can match the above:

preg_match('/^(?=.*[0-9])[- +()0-9\r\n\t]+$/', $value)

But I need to negate it, to match whenever the value being compared is NOT it. Would really appreciate any prompt help I can get.

Thank you.

user627341
  • 79
  • 8
  • Can you show a sample input, as well as what the resulting array should be? – Chris Haas Nov 24 '21 at 12:53
  • Looks like you should just use `'/[^\d()+\n\t-]/'` with `preg_split`. Why did you switch to `preg_match`? – Wiktor Stribiżew Nov 24 '21 at 12:53
  • @WiktorStribiżew didn't switch to `preg_match`, was just trying to show the other regex I attempted to use. Thanks for the input, will try it out. – user627341 Nov 24 '21 at 13:00
  • @ChrisHaas sample input is any string that contains both alphabets, numbers and symbols. Should count from the beginning and split whenever it encounters a character that is NOT a number, bracket, plus sign, hyphen, newline or tab. – user627341 Nov 24 '21 at 13:03

1 Answers1

1

The [a-zA-Z] pattern matches any ASCII letter. Any char "NOT a number, bracket, plus sign, hyphen, newline or tab" can also be a letter, so you should focus on the latter requirement, your former pattern is no longer relevant.

You should keep using preg_split:

$splitOriginal = preg_split('/[^\d()+\n\t-]/', implode('', array_slice($array, $key)), 2);

The [^\d()+\n\t-] pattern matches exactly what you formulated. Pay attention at the hyphen, when it is at the end (or start) of the character class, it can go unescaped.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563