replace content tags with callback via regex


/ Published in: PHP
Save to your folder(s)



Copy this code and paste it in your HTML
  1. /**
  2.  * Replace all tags matching a regexp with value of callback function
  3.  * (passes grouped subpatterns to callback as params)
  4.  */
  5. function my_wp_plugin_tag_action($content,$tag,$function,$args = FALSE) {
  6. // match all regular expressions
  7. preg_match_all($tag,$content,$matches);
  8. if (count($matches)>0) {
  9. // filter duplicates
  10. $matches = array_unique($matches);
  11. // loop through
  12. $tag_results = array();
  13. $found_tags = array();
  14. foreach ($matches as $idx => $match) {
  15. //build arg array
  16. $full_tag = array_shift($match);
  17. //call function, adding function output and full tag text to replacement array
  18. $tag_results[] = my_wp_plugin_buffer_func($function,$match);
  19. $found_tags[] = $full_tag;
  20. }
  21. // replace all tags with corresponding text
  22. $content = str_replace($found_tags,$tag_results,$content);
  23. }
  24. return $content;
  25. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.