Drew Drew - 1 month ago 8
PHP Question

Quick regex help match same symbol

I am trying to get a regex to grab all the same symbol in a row.

\W or \W+ do not work.

eg

"===--,,,--;[]'"


array(
[0] => ===
[1] => --
[2] => ,,,
[3] => --
[4] => ;
[5] => [
[6] => ]
[7] => '
)


I do not need the code to get it into an array. I got that working. Just the regex portion to grab repeat symbols.

Answer

In order to check for a repeat part in regex you need to use the backreferences.

Here is an example in javascript:

a = "===--,,,--;[]'"
t = a.match(/(.)(\1*)/g)
console.log(t)

Here is a code in php:

preg_match_all("/(.)(\\1*)/", "===--,,,--;[]'", $m);
var_dump($m[0]);

Output:

array(8) {
  [0]=>
  string(3) "==="
  [1]=>
  string(2) "--"
  [2]=>
  string(3) ",,,"
  [3]=>
  string(2) "--"
  [4]=>
  string(1) ";"
  [5]=>
  string(1) "["
  [6]=>
  string(1) "]"
  [7]=>
  string(1) "'"
}

If you want to specify only these specific chars you can use:

preg_match_all("/([=\-,;\[\]'])(\\1*)/", "===--,,,--;[]'", $m);
var_dump($m[0]);