Home > Blockchain >  PHP preg_split() if it is NOT a number, sign, bracket, new line or tab
PHP preg_split() if it is NOT a number, sign, bracket, new line or tab

Time:11-24

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.

CodePudding user response:

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.

  • Related