2

I'm trying to solve some problem and I need to split repeated chars and all integers

$code = preg_split('/(.)(?!\1|$)\K/', $code);

I tried this one, but it separate and not repeated chars and not repeated integers , I need only chars

I have a string 'FFF86C6'

I need an array (FFF, 86, C, 6);

with pattern '/(.)(?!\1|$)\K/' returns (FFF, 8, 6, C, 6)

Do you have any idea how to make it?

Rahul Singh
  • 918
  • 14
  • 31

1 Answers1

1

You can use this regex with preg_match_all:

([A-Za-z])(\1*)|\d+

It looks for a letter, followed by some number of the same character, or some digits. By using preg_match_all we find all matches in the string. Usage in PHP:

$string = "FFF86CR6";
$pieces = preg_match_all('/([A-Za-z])(\1*)|\d+/', $string, $matches);
print_r($matches[0]);

Output:

Array (
  [0] => FFF
  [1] => 86
  [2] => C
  [3] => R
  [4] => 6 
)

Demo on 3v4l.org

Nick
  • 138,499
  • 22
  • 57
  • 95
  • Thanks a lot, maybe you know how to add ')' and '(' to this pattern? So if there are bracket in string it will also appear in array as single element. Those patterns are a bit painful for me :( – Olga Kriukova May 15 '19 at 11:04
  • @OlgaKriukova can you give me an example of what you mean? – Nick May 15 '19 at 11:09
  • if string 'FFF3RF(5' after preg_match_all : array('FFF', '3', 'R', 'F', '(', '5'); – Olga Kriukova May 15 '19 at 11:12
  • @OlgaKriukova just add a character class for `(` and `)` to the regex. See https://3v4l.org/8Vl5a – Nick May 15 '19 at 11:14