Using the preg_match_all('~[,()^/*+-]~', $e, $m) and preg_split("/\,|\(|\)|\^|\/|\*|\-|\+/",$e); I break a string into an array of specific words.

I need to separate the string by words different from ^ ( , ) , ^ , / , * , - , + and not different from them.

For example:

 pi*t+(a/c) 

In array(array('*','+','/'),array(pi,t,a,c)) .

My preg_split("/\,|\(|\)|\^|\/|\*|\-|\+/",$e); leaves empty elements in the resulting array.

  • What do you mean? The comma is not a word, like the other characters ()^/*-+ . Give an example. - Wiktor Stribiżew
  • [^,\(\)\^\/\*\-\+] - this syntax is used. The sign of denial is ^ - iosp
  • @iosp: Only without a slash - [^,()^/*+-] . Maybe preg_split('~[^,()^/*+-]+~', $e) ? Without examples it is difficult to understand exactly what is required. - Wiktor Stribiżew
  • @Wiktor Stribiżew not sure about the slashes, usually escapes special characters in reg. expression. It definitely doesn't hurt. - iosp
  • Give an example (s). In the question itself, not in the comments. - Wiktor Stribiżew

1 answer 1

Instead of splitting the string, you need to find all the matches of the characters you are looking for using preg_match_all :

 // Всё вместе $e = "a+d+c/t-(a*r)"; preg_match_all('~[^,()^/*+-]+|[,()^/*+-]~', $e, $m); print_r($m[0]); // Только все "слова" preg_match_all('~[^,()^/*+-]+~', $e, $m1); print_r($m1[0]); // Только все "символы" preg_match_all('~[,()^/*+-]~', $e, $m2); print_r($m2[0]); 

See online demo

Since ~ used as delimiters, backslash must not be escaped / escaped. Since - placed at the end of the character class, it is also not necessary to screen it. ^ not in the initial position in the character class is also not necessary to escape. ,()*+ are literally always interpreted in character classes.

  • I changed the question - lexa kop
  • @lexakop Ie need to get an array of "tokens". The answer is updated. - Wiktor Stribiżew
  • Thank you, you understood me correctly, everything works. - lexa kop