fork download
  1. <?php
  2. $input = <<<'EOF'
  3. 1....X.......
  4. 2..X..X...X....
  5. 3X.X...X..X.....
  6. 4X....XXXXXX.....
  7. 5X..XXX...........
  8. 6.....X..........
  9. 7.........X....X
  10. 8..X......X....X....
  11. 9..X......X....X....X...
  12. A....X.....
  13. B.X..X..
  14. C.....
  15. DXXX
  16. EXXX
  17. FXXX
  18. EOF;
  19.  
  20. $pattern = '/
  21. ^
  22. (?:(?|
  23. (?(5)(?![\s\S]*+\5))
  24. (?!(?!)()())
  25. (?=
  26. (?:
  27. .
  28. (?=
  29. .*+\n
  30. ( \3? . )
  31. .*+\n
  32. ( \4? . )
  33. )
  34. )*?
  35. X .*+\n
  36. \3
  37. X .*+\n
  38. \4
  39. X
  40. )
  41. ()
  42. |
  43. (?(5)(?=[\s\S]*+\5)|(?!))
  44. (?:
  45. .
  46. (?=
  47. .*+\n
  48. ( \1? .)
  49. .*+\n
  50. ( \2? .)
  51. )
  52. )+?
  53. (?=
  54. (?<=X) .*+\n
  55. (\1)
  56. (?<=X) .*+\n
  57. (\2)
  58. (?<=X)
  59. )
  60. (?=
  61. ([\s\S])
  62. [\s\S]*
  63. (. (?(6)\6))
  64. )
  65. ){2})+
  66. /xm';
  67.  
  68. echo "Input:\n", $input;
  69.  
  70. $str = preg_replace_callback($pattern,
  71. function($match) {
  72. return '!' . $match[0];
  73. }
  74. , $input);
  75.  
  76. $str = preg_replace('/^(?!!)/m', '-', $str);
  77.  
  78. echo "\n\nLines containing at least one match are marked with '!':\n", $str;
  79.  
  80. preg_match_all($pattern, $input, $matches);
  81. echo "\n\nThis is group 6 for each match. Each subarray represents a
  82. matching line. The amount of characters indicates how many matches there are
  83. in that particular line. You could find out which line this corresponds to
  84. by using PREG_CAPTURE_OFFSET and inspecting group 0 (the entire match).";
  85. print_r($matches[6]);
  86. ?>
Success #stdin #stdout 0.01s 20568KB
stdin
Standard input is empty
stdout
Input:
1....X.......
2..X..X...X....
3X.X...X..X.....
4X....XXXXXX.....
5X..XXX...........
6.....X..........
7.........X....X
8..X......X....X....
9..X......X....X....X...
A....X.....
B.X..X..
C.....
DXXX
EXXX
FXXX

Lines containing at least one match are marked with '!':
-1....X.......
!2..X..X...X....
!3X.X...X..X.....
!4X....XXXXXX.....
-5X..XXX...........
-6.....X..........
!7.........X....X
-8..X......X....X....
-9..X......X....X....X...
-A....X.....
-B.X..X..
-C.....
!DXXX
-EXXX
-FXXX

This is group 6 for each match. Each subarray represents a
    matching line. The amount of characters indicates how many matches there are
    in that particular line. You could find out which line this corresponds to
    by using PREG_CAPTURE_OFFSET and inspecting group 0 (the entire match).Array
(
    [0] => X
    [1] => X
    [2] => X
    [3] => XX
    [4] => XXX
)