Pomoc - Szukaj - Użytkownicy - Kalendarz
Pełna wersja: [PHP][Wyrażenia regularne] tworzenie linków
Forum PHP.pl > Forum > Przedszkole
woj_tas
Witam

Potrzebuje z tekstu wyciągnąć wszystkie adresy stron i zamienić je na linki.

Napisałem taki o to kod:
  1. $text = preg_replace(array('#http://[^\s]+#e', '#www.[^\s]+#e'), array("'<a href=\"'.htmlspecialchars('\\0').'\" target=\"projekt\">'.htmlspecialchars('\\0').'</a>'", "'<a href=\"http://'.htmlspecialchars('\\0').'\" target=\"projekt\">'.htmlspecialchars('\\0').'</a>'"), $text);


który wysypuje się przy strukturze linka:
http://www.onet.pl

Działa poprawnie dla:
http://onet.pl
www.onet.pl

Ma ktoś jakiś pomysł?
kilas88
Nie chce mi się pisać wyrażenia regularnego, ale może by pójść na skróty i wykorzystać DOM?

Pierwszy lepszy przykład:

  1. <?php
  2. /**
  3.  * @author Jay Gilford
  4.  */
  5.  
  6. /**
  7.  * get_links()
  8.  *
  9.  * @param string $url
  10.  * @return array
  11.  */
  12. function get_links($url) {
  13.  
  14. // Create a new DOM Document to hold our webpage structure
  15. $xml = new DOMDocument();
  16.  
  17. // Load the url's contents into the DOM
  18. $xml->loadHTMLFile($url);
  19.  
  20. // Empty array to hold all links to return
  21. $links = array();
  22.  
  23. //Loop through each <a> tag in the dom and add it to the link array
  24. foreach($xml->getElementsByTagName('a') as $link) {
  25. $links[] = array('url' => $link->getAttribute('href'), 'text' => $link->nodeValue);
  26. }
  27.  
  28. //Return the links
  29. return $links;
  30. }
  31. ?>
To jest wersja lo-fi głównej zawartości. Aby zobaczyć pełną wersję z większą zawartością, obrazkami i formatowaniem proszę kliknij tutaj.
Invision Power Board © 2001-2025 Invision Power Services, Inc.