Posted By

caioariede on 04/07/09


Tagged

regex php replace text syntax


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

vali29
sapphiriq


Regex Text Syntax Parser


 / Published in: PHP
 

URL: http://caioariede.com/

Parse syntax in a text using pregreplacecallback.

  1. <?php
  2.  
  3. class Parser
  4. {
  5. public $func_expr = '!\[#(.+?)(?:\s(.+?))?\]!s';
  6. public $args_expr = '!(\S+)\s*=\s*([\'"]?)([^\2]+?)\2!s';
  7.  
  8. public function __construct($text, $cbclass)
  9. {
  10. $this->_text = $text;
  11. $this->_cbclass = $cbclass;
  12. }
  13.  
  14. public function func_expr($expr = NULL)
  15. {
  16. return empty($expr) ? $this->func_expr : $this->func_expr = $expr;
  17. }
  18.  
  19. public function args_expr($expr = NULL)
  20. {
  21. return empty($expr) ? $this->args_expr : $this->args_expr = $expr;
  22. }
  23.  
  24. public function do_parse()
  25. {
  26. return preg_replace_callback($this->func_expr, array($this, 'do_parse_func'), $this->_text);
  27. }
  28.  
  29. private function do_parse_func($m)
  30. {
  31. list(, $func, $args) = $m;
  32. $args = $this->do_parse_args($args);
  33. return call_user_func($this->_cbclass . '::' . $func, $args);
  34. }
  35.  
  36. private function do_parse_args($str)
  37. {
  38. preg_match_all($this->args_expr, $str, $m);
  39. if (empty($m[3])) return NULL;
  40. return array_combine($m[1], $m[3]);
  41. }
  42. }
  43.  
  44. class MyParserCallbacks
  45. {
  46. public static function func($args)
  47. {
  48. //var_dump($args);
  49. return 'REGEXFTW';
  50. }
  51. }
  52.  
  53. $text = '[#func] blabla [#func tamanho="520x75"] teste [#func tamanho="520x75"]';
  54.  
  55. $parser = new Parser($text, MyParserCallbacks);
  56. echo $parser->do_parse();
  57.  
  58. ?>

Report this snippet  

You need to login to post a comment.