Posted By

pateketrueke on 06/14/08


Tagged

php html replace highlight bbcode


Versions (?)

Highlight within HTML/BBCode without source breaking


 / Published in: PHP
 

  1. /**
  2.  * (contexto[, busqueda[, reemplazo[, ordinal]]])
  3.  *
  4.  * Resalta palabras dentro de una cadena de texto.
  5.  */
  6. function search($text, $find, $repl = '<strong>\\1</strong>', $ord = 32)
  7. {
  8. global $tags, $num;
  9.  
  10. $num = 0; // contador
  11. $tags = array(); // pila
  12.  
  13. $char = is_numeric($ord)?
  14. chr($ord): $ord[0]; // caracter?
  15.  
  16. if (!function_exists('_search_backup_tags'))
  17. { // guardamos el HTML
  18. function _search_backup_tags($test)
  19. {
  20. global $tags, $num;
  21. // guardamos el tag completo
  22. $tags[$num] = $test[0];
  23.  
  24. $tag = "<!$num>";
  25. $num++; // pisa y corre!
  26. return $tag;
  27. }
  28. }
  29. if (!function_exists('_search_restore_tags'))
  30. { // recuperamos el HTML
  31. function _search_restore_tags($test)
  32. {
  33. global $tags; // xD
  34. return $tags[$test[1]];
  35. }
  36. }
  37.  
  38. $text = // escapamos tags tipo HTML/BBCode
  39. preg_replace_callback('/([<\[][^>\]]+\/?[\]>])/', '_search_backup_tags', $text);
  40.  
  41. // ----------------------------- Resaltamos!
  42. $found = array();
  43. $word = // separamos en palabras?
  44. explode($char, $find);
  45.  
  46. foreach ($word as $test)
  47. { // Escapamos las "wildcards"
  48. $found[] = preg_quote(strip_tags($test));
  49. }
  50.  
  51. $expr = join('|', $found); // unimos
  52. $text = // Aqui ocurre toda la magia....
  53. preg_replace("/($expr)/is", $repl, $text);
  54.  
  55.  
  56. // recuperamos etiquetas HTML/BBCode
  57. $text = preg_replace_callback('/<!(\d+)>/', '_search_restore_tags', $text);
  58.  
  59. return $text;
  60. }

Report this snippet  

You need to login to post a comment.