Skip to content

Instantly share code, notes, and snippets.

@marlenesco
Last active January 21, 2020 10:04
Show Gist options
  • Save marlenesco/6078556 to your computer and use it in GitHub Desktop.
Save marlenesco/6078556 to your computer and use it in GitHub Desktop.
Convert simple text in full html.Image links will convert in <IMG> tagsUrl links will convert in <A> tags
<?php
/**
* Convert simple text to full html
* Image links will convert in <IMG> tags
* Url links will convert in <A> tags
*
* @param string $str the text to convert
* @param string $cssClass css class for tags
* @param boolean $strip_tags init strip html tags
* @return string
*/
function autoText($str, $cssClass = "", $strip_tags = true) {
if (empty($str))
return "";
if ($strip_tags === true)
$str = strip_tags($str);
$str = ' ' . $str;
$img_pattern = '`([^"=\'])((http|https|ftp)://[^\s<]+[^\s<\.)]+.(jpg|png|gif))`i';
$link_pattern = '`([^"=\'])((http|https|ftp)://[^\s<]+[^\s<\.)])`i';
if (preg_match($img_pattern, $str, $a, PREG_OFFSET_CAPTURE)) {
$str = preg_replace(
$img_pattern,
"\n". '<img src="$2" class="autotext img_autotext '. $cssClass .'" />'."\n",
$str
);
}
if (preg_match($link_pattern, $str, $b, PREG_OFFSET_CAPTURE)) {
$str = preg_replace(
$link_pattern,
'$1<a target="_blank" rel="nofollow" class="autotext a_autotext '. $cssClass .'" href="$2">$2</a>',
$str
);
}
while (strpos($str, "\n\n") !== false) {
$str = str_replace("\n\n", "\n", $str);
}
$strA = explode("\n", $str);
if (count($strA) > 1)
$str = '<p class="autotext p_autotext '. $cssClass .'">'. implode('</p><p class="autotext p_autotext '. $cssClass .'">', $strA) .'</p>';
else
$str = '<p class="autotext p_autotext '. $cssClass .'">'. implode('', $strA) .'</p>';
return $str;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment