PHP - Cortar link /url dentro de string


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



Copy this code and paste it in your HTML
  1. function get_links($string) {
  2. $patron='/\<a href\=(.*?)\>(.*?)\<\/a\>/is';
  3. preg_match_all ($patron, $string,$coincidencias);
  4. return $coincidencias[0];
  5. };
  6. function get_links_text($string) {
  7. $patron='#[^<ref=">]http\:\/\/([^"<>]*)#is';
  8. preg_match_all ($patron, $string,$coincidencias);
  9. return $coincidencias[0];
  10.  
  11. };
  12. function redlink($link,$largopartes){
  13. $patron='/\<a href\=(.*?)\>(.*?)\<\/a\>/i';
  14. preg_match_all ($patron, $link,$coincidencias);
  15. $s='/\<a href\=(.*?)\>(.*?)\<\/a\>/se';
  16. if(strlen($coincidencias[2][0])>($largopartes<<1))
  17. $r='"<a href=$1>".substr("$2",0,"$largopartes")."...".substr("$2","-$largopartes")."</a>"';
  18. else
  19. $r='"<a href=$1>$2</a>"';
  20. $t=preg_replace ($s, $r, $link);
  21. return $t;
  22. }
  23.  
  24. function redlink2($link,$largopartes){
  25. if(strlen($link)>($largopartes<<1))
  26. $r='<a href="'.$link.'">'.substr($link,0,$largopartes).'...'.substr($link,-$largopartes).'</a>';
  27. else
  28. $r='<a href="'.$link.'">'.$link.'</a>';
  29. return $r;
  30. }
  31.  
  32. $cadena='
  33. um fringilla commodo, magna metus tempus justo, quis eleifend enim ante vel nisl. Nam tellus ligula, semper eu, pretium et, placerat sit amet, justo. Phasellus sagittis faucibus orci. Phasellus ultricies scelerisque nulla. Quisque metus. Aliquam leo dolor, pellentesque eu, cursus sollicitudin, porta a, velit.
  34. hola http://www.akjhas.dasa/asdasda/asasa/asasa/asasasas/asas.pl <br><a href="http://www.google.com.ar">Este es un magnífico buscador y en él hay de todo</a>
  35. Nunc pulvinar. In porta nisl vitae magna. Nunc justo libero, feugiat at, dignissim sed, interdum eleifend, est. In ornare pellentesque odio. Ut mauris. Donec ornare vestibulum urna. Vestibulum et massa. Integer viverra, nisl ac congue elementum, nisi felis dignissim sapien, et adipiscing nisl urna a ligula. In mattis imperdiet dui. Fusce tincidunt mauris sed massa. Aenean at nisl. Sed enim ante, aliquam non, sagittis non, consequat et, dui. Aliquam faucibus adipiscing lacus. Praesent sem velit, scelerisque sit am
  36. ';
  37. $links=get_links($cadena);
  38. $urls=get_links_text($cadena);
  39. foreach($links as $v){
  40. $replace[]=redlink($v,15);
  41. }
  42. foreach($urls as $v){
  43. $replace[]=redlink2($v,15);
  44. }
  45. $search=array_merge($links,$urls);
  46.  
  47. echo str_replace($search,$replace,$cadena);

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.