Witaj Gościu! ( Zaloguj | Rejestruj )

Forum PHP.pl

> [PHP][Wyrażenia regularne] tworzenie linków
woj_tas
post
Post #1





Grupa: Zarejestrowani
Postów: 230
Pomógł: 36
Dołączył: 31.03.2006
Skąd: Zielona Góra

Ostrzeżenie: (0%)
-----


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ł?

Ten post edytował woj_tas 9.07.2010, 13:26:51


--------------------
Go to the top of the page
+Quote Post
 
Start new topic
Odpowiedzi (1 - 1)
kilas88
post
Post #2





Grupa: Zarejestrowani
Postów: 305
Pomógł: 25
Dołączył: 27.01.2007

Ostrzeżenie: (0%)
-----


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. ?>


Ten post edytował kilas88 9.07.2010, 13:58:13
Go to the top of the page
+Quote Post

Reply to this topicStart new topic
1 Użytkowników czyta ten temat (1 Gości i 0 Anonimowych użytkowników)
0 Zarejestrowanych:

 



RSS Aktualny czas: 21.08.2025 - 12:29