Visita Orebla.it su Facebook Segui Orebla.it su Twitter Vedi i video su YouTube di Orebla.it Unisciti alle cerchie di Orebla.it
DOVE TI TROVI: \\ Home Page\php\PHP Preg_Replace Preg_match: manipolare, convalidare URL

Imparare il PHP: Manipolazione URL con Preg_replace e Preg_match

autore: Orebla
09/02/11

Manipolare URL con Preg_replace e Preg_match:

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:

  1. Rendere un URL di testo cliccabile con TAG HTML;
  2. Rimuovere il collegamento, quindi il contrario del primo punto;
  3. Validare un URL e verificare se è correttamente scritto;
  4. Verificare se un URL punta verso l'esterno, aggiungere poi un'immagine che indica l'esternalità del link.

 

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!):

/**
* Method to take a string and return it with URLS with http:// or ftp://
* and email addresses as active links. I based this on code that I saw
* somewhere, but unfortunately, I cannot remember where I saw it. Feel free
* to let me know if you see any code here that is your idea, and I will credit
* you.
*
* @param string $str The string to be parsed
* @return the parsed string
*/
function makeClickableLinks($str)
{
// Exclude matched inside anchor tags
$not_anchor = '(?<!"|href=|href\s=\s|href=\s|href\s=)';
// Match he protocol with ://, e.g. http://
$protocol = '(http|ftp|https):\/\/';
$domain = '[\w]+(.[\w]+)';
$subdir = '([\w\-\.;,@?^=%&:\/~\+#]*[\w\-\@?^=%&\/~\+#])?';
$test = '/' . $not_anchor . $protocol . $domain . $subdir . '/i';
// Match and replace where there is a protocol and no anchor
$ret = preg_replace($test, "<a href='$0' title='$0'>$0</a>", $str);
// Now match things beginning with www.
$not_anchor = '(?<!"|href=|href\s=\s|href=\s|href\s=)';
$not_http = '(?<!:\/\/)';
$domain = 'www(.[\w]+)';
$subdir = '([\w\-\.;,@?^=%&:\/~\+#]*[\w\-\@?^=%&\/~\+#])?';
$test = '/' . $not_anchor . $not_http . $domain . $subdir . '/is';
return preg_replace($test, "<a href='http://$0' title='http://$0'>$0</a>", $ret);
}

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:

/**
* Checks if a URL is validly formed based on the code in
* PHP Classes by Lennart Groetzbach <lennartg_at_web_dot_de>
* Adapted to KINKY by Derek
*
* @param String $str The Url to validate
* @param boolean $strict Enforce strict checking?
* @return boolean TRUE|FALSE
*/
function isValidFormedUrl($str, $strict = false)
{
$test = "";
if ($strict == true) {
$test .= "/^http:\\/\\/([A-Za-z-\\.]*)\\//";
} else {
$test .= "/^http:\\/\\/([A-Za-z-\\.]*)/";
}
return @preg_match($test, $str);
}

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:

  1. $str -> indica la stringa da analizzare, contenente l'URL;
  2. $activ -> se impostata su TRUE rende l'icona cliccabile come collegamento, se impostata su FALSE aggiunge l'icona dopo il link; di DEFAULT e TRUE;
  3. $repl -> questa è la stringa contenente il codice HTML da aggiungere alla fine, oppure come icona (vedi punto 2), che serve ad identificare il link esterno. Possiamo direttamente creare noi il codice HTML con l'icona, oppure semplicemente lasciarla vuota ed impostare la variabile $exterIcon con il nome dell'immagine!





Articoli utili:
Jailbreak iOS 10: tweaks compatibili

Recensione iPhone 6

IPhone 7 uscito, novita, prezzi