Oggi parliamo di come è possibile utilizzare la funzione preg_replace di PHP per eseguire molte cose interessanti relativamente agli URL.
Vediamo, utilizzando come esempio un'ottima classe, come è possibile:
Anzitutto voglio mettere il link da dove potete scaricare la classe che contiene tutte queste funzioni: Active URL.
RENDIAMO CLICCABILE UNA STRINGA CONTENENTE UN URL:
Analizziamo il codice necessario per fare questo lavoro (trovate tutto all'interno della classe a cui ho fatto riferimento prima!):
Questa funzione riceve come input la stringa contenente l'URL e, in automatico, gli aggiunge il TAG <a> in modo da restituire, come output, l'indirizzo URL cliccabile.
Come potete vedere lo script analizza il testo dato come input e con la prima parte rende l'indirizzo scritto con la giusta sintassi e poi lo trasforma in codice HTML.
DISATTIVIAMO IL COLLEGAMENTO IPERTESTUALE:
La seconda funzione, invece, serve per l'esatto contrario: toglie qualsiasi riferimento con TAG HTML trasformando tutto il codice HTML senza alcun Link cliccabile.
/**
* Method to unlink URLs in text. The numbers in the comments refer
* to the backreferences for matches inside parentheses ()
*
* @param string $str The string to be parsed
* @return the parsed string
*/
function removeLinks($str)
{
$test="/(<a\s+href=)" //1: Match the start of the anchor tag followed by
// any number of spaces followed by href followed
."([\"\'])" //2: Match either of " or ' and remember it as \2 for a backreference
. "(.*[\"'])" //3: Match any characters up to the next " or '
. "(.*>)" //4: Anything else followed by the closing >
. "(.+)" //5: Match any string of 1 or more characters
. "(<\/a>)" //6: Match the closing </a> tag
. "/isU"; //Make it case insensitive (i), treat across newlines (s)
//and make it Ungreedy (U)
return preg_replace($test, "\$5", $str);
}
COME VALIDARE UN URL CON PHP:
Questa penso sia la funzione più interessante di questa classe, dato che ci permette di convalidare un URL. Verificando se è correttamente scritto. Funzione molto valida se vogliamo utilizzare la classe per uno script in cui chiediamo agli utenti di inserire il proprio indirizzo web:
In sintesti questa funzione utilizzare preg_match. Tale funzione di PHP serve a verificare che le condizione che diamo come input siano rispettate. Nel nostro caso verifichiamo che l'URL inizi con il canonico http:// e poi contenga solamente lettere maiuscole o minuscole (questa versione non contempla i numeri ma può benissimo essere modificata!) e i caratteri che rispettano il protocollo HTTP.
VERIFICARE SE UN URL PUNTA VERSO UN ALTRO DOMINIO DA DOVE È OSPITATO:
/**
* Method to add something to the end of an external link
* where external is defined as one that starts with http://
* or ftp://
* It uses a perl type regular expression
* Ir was made with help from participants in the
* Undernet IRC channel #phphelp
* @author Derek Keats
* @param String $str The string to be tagged
* @param String $activ Whether to make the $repl or icon active, default TRUE
* @param String $repl The string to add to the end of the link
* Defaults to the external link icon
* @return String The string with external links tagged
*/
function tagExtLinks($str, $activ=true, $repl = null)
{
if ($repl == null) {
$exterIcon = 'external_link.gif';
$repl = '<img src="' . $exterIcon . '" alt="Open in a new window" border="0">';
}
if ($activ==null) {
$test = "/(<a\s+href=)" // 1: Match the opening of the anchor tag
."(\"|\')" // 2: Match the first single or double quotes
."(http|https|ftp)" // 3: match the protocol identifier (Http, ftp, https)
."(:\/\/)" //4: Match the :// part of the URL
."(?!" . $_SERVER['HTTP_HOST'] . ")" // 5: Do not match if it is the local server
."(.*)" // 6: Match any number of following characters up to the closing anchor tag
."(<\/a>)/isU"; // 7: Match the closing anchor tag
return preg_replace($test, " \${0}" . $repl, $str);
} else {
$test = "/(<a\s+href=)" // 1: Match the opening of the anchor tag
."(\"|\')" // 2: Match the first single or double quotes
."(http|https|ftp)" // 3: match the protocol identifier (Http, ftp, https)
."(:\/\/)" //4: Match the :// part of the URL
."(?!" . $_SERVER['HTTP_HOST'] . ")" // 5: Match domain but exclude the local server
."(.*)" // 6: Match any characters after the server
."(\"|\')" //7: Match a closing single or double quote (helps pull out the URL)
."(.*)" // 8: Match any further characters
."<\/a>/isU"; // 9: Match the closing anchor
return preg_replace($test,
" \${0} <a href=\"\${3}\${4}\${5}\"
target=\"_BLANK\">" . $repl . "</a>", $str);
}
}
Illustriamo questa splendida funzione. Prima di tutto gli elementi in input che attende per funzionare sono 3: