fork download
  1. <?php
  2. function ParseText($text) {
  3. $re = '/\[\[(?P<DoubleBracket>.*?)]]|\[(?P<Bracket>.*?)]|\((?P<Paren>.*?)\)|(?<Arrow><---+>?|---+>)/s';
  4. $keys = array('DoubleBracket', 'Bracket', 'Paren', 'Arrow');
  5. $result = array();
  6. $lastStart = 0;
  7. if (preg_match_all($re, $text, $matches, PREG_SET_ORDER | PREG_OFFSET_CAPTURE)) {
  8. foreach ($matches as $match) {
  9. $start = $match[0][1];
  10. $prefix = substr($text, $lastStart, $start - $lastStart);
  11. $lastStart = $start + strlen($match[0][0]);
  12. if ($prefix != '' && !ctype_space($prefix)) {
  13. $result []= array('Text', trim($prefix));
  14. }
  15. foreach ($keys as $key) {
  16. if (isset($match[$key]) && $match[$key][1] >= 0) {
  17. $result []= array($key, $match[$key][0]);
  18. break;
  19. }
  20. }
  21. }
  22. }
  23. $prefix = substr($text, $lastStart);
  24. if ($prefix != '' && !ctype_space($prefix)) {
  25. $result []= array('Text', trim($prefix));
  26. }
  27. return $result;
  28. }
  29.  
  30. $mytext = <<<'EOT'
  31. Text Text [something]
  32. --->
  33. Text (something 021213)
  34. More Text
  35. EOT;
  36.  
  37. $parser = ParseText($mytext);
  38. foreach ($parser as $item) {
  39. print_r($item);
  40. }
  41. ?>
  42.  
Success #stdin #stdout 0.01s 20568KB
stdin
Standard input is empty
stdout
Array
(
    [0] => Text
    [1] => Text Text
)
Array
(
    [0] => Bracket
    [1] => something
)
Array
(
    [0] => Arrow
    [1] => --->
)
Array
(
    [0] => Text
    [1] => Text
)
Array
(
    [0] => Paren
    [1] => something 021213
)
Array
(
    [0] => Text
    [1] => More Text
)