Função PHP que detecta links no formato de texto e transforma em links HTML

Função PHP que detecta um link em formato de texto e transforma o link no formato HTML.

function identifyLinkInString($string){
	if(!is_string($string)){ return $string; }

	$expression = "/((http|https|ftp|ftps):\/\/(www\.|.*?\/)?|www\.)([a-zA-Z0-9]|_|-)+(\.(([0-9a-zA-Z]|-|_|\/|\?|=|&|&|&)+))+/i";
	preg_match_all($expression, $string, $match);
	
	foreach($match[0] AS $search_link_text){
		/**
		 * Insert http:// if not exists
		 */
		$link_text_origin = $search_link_text; 
		if(stristr($search_link_text, "http://") === false && stristr($search_link_text, "https://") === false){
			$link = "http://" . $search_link_text;
		}else{
			$link = $search_link_text;
		}
		
		$link_lenght = strlen($link_text_origin);

		$link_name = str_replace(['&','&'], ['&','&'], $link);

		$string = str_ireplace ($link_text_origin, '<a href="'.$link.'" target="_blank">'.(($link_lenght > 60) ? substr ($link_name, 0, 25). "...". substr ($link_name, -15) : $link_name).'</a>', $string);	
	}

	return $string;
}

Exemplo de uso:

<?php
$string = "Exemplo de url em formato de texto www.brunogoulart.com.br que a função transforma em link html. Outros formatos de url: https://brunogoulart.com.br/funcao-php-que-detecta-links-no-formato-de-texto-e-monta-no-formato-html/";
echo identifyLinkInString($string);

?>

Resultado:

“Exemplo de url em formato de texto http://www.brunogoulart.com.br que a função transforma em link html. Outros formatos de url: https://brunogoulart.com….o-formato-html/“.


Suporta a maioria das url. Porém url complexas não são suportadas.
Se tiverem sugestões , por favor, colaborem nos comentários.

Sobre Bruno

Simplesmente um Programador

Deixe um comentário

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *