2010-11-18 20 views
9

Ho una funzione che aggiungerà il tag <a href> prima di un collegamento e </a> dopo il collegamento. Tuttavia, si interrompe per alcune pagine Web. Come miglioreresti questa funzione? Grazie!PHP - Aggiungi il link a un URL in una stringa

function processString($s) 
{ 
    // check if there is a link 

    if(preg_match("/http:\/\//",$s)) 
    { 
     print preg_match("/http:\/\//",$s); 


     $startUrl = stripos($s,"http://"); 

     // if the link is in between text 
     if(stripos($s," ",$startUrl)){ 
      $endUrl = stripos($s," ",$startUrl); 
     } 
     // if link is at the end of string 
     else {$endUrl = strlen($s);} 

     $beforeUrl = substr($s,0,$startUrl); 
     $url = substr($s,$startUrl,$endUrl-$startUrl); 
     $afterUrl = substr($s,$endUrl); 

     $newString = $beforeUrl."<a href=\"$url\">".$url."</a>".$afterUrl; 

     return $newString; 
    } 

    return $s; 
} 
+0

La regex è un po 'sciatto, ma il 99% del mio ingresso avrà URL corretti eventuali – AlexBrand

+4

Cosa pagine web non è per rompere? –

+0

All'inizio si prova anche https agains, ma in seguito si omette la "s". Non so, se questo causa questo errore, perché anche io non so, quali pagine sono rotte;) – KingCrunch

risposta

18
function processString($s) { 
    return preg_replace('/https?:\/\/[\w\-\.!~#?&=+\*\'"(),\/]+/','<a href="$0">$0</a>',$s); 
} 
+0

Penso che manchi "=": fallisce quando l'url contiene i parametri get. L'ho appena aggiunto dopo "&" e ora funziona: 'preg_replace ('/ https?: \/\/[\ W \ - \.! ~? & = + \ * \'"(), \ /] +/',' $0 ', $ s) ' – Narcolessico

+4

Hai dimenticato gli indirizzi con # all'interno - quindi la versione più corretta è' preg_replace ('/https?: \/\/[\ W \ - \.! ~ # ? & = + \ * \ '"(), \ /] + /', '$0', $ text)' –

+0

Ho appena modificato la risposta per riflettere queste due aggiunte. –

1

Si rompe per tutti gli URL che contengono caratteri HTML "speciali". Per sicurezza, passare i tre componenti della stringa tramite htmlspecialchars() prima di concatenarli insieme (a meno che non si desideri consentire l'HTML all'esterno dell'URL).

1
function processString($s){ 
    return preg_replace('@((https?://)?([-\w]+\.[-\w\.]+)+\w(:\d+)?(/([-\w/_\.]*(\?\S+)?)?)*)@', '<a href="$1">$1</a>', $s); 
} 

Trovato here

+0

non riesce qui: ' http: //www.xyz.com/~this-does-not-work! ' – stillstanding

+0

corrisponde a" a ... a "- strano – AlexBrand

+0

Lo stesso scenario ne ho bisogno in Jquery/Javascript. Qualcuno può aiutarti? – Yuv

Problemi correlati