Auto Paragraph Function with URL Parsing and Smilie Detection

on in Blog
Last modified on

This function emulates WordPress wpautop() function for custom PHP scripts, parses URL addresses and adds smilies/emoticons. If you’re coding your own CMS or string parsing library, it could be useful.

Note: Smilies not included 😢

  • First of all, the function changes 2 line breaks (HTML <br>) into a paragraph.
  • Second, the function changes the remaining single line breaks into HTML <br>, making a SHIFT+ENTER new line.
  • Third, the function parses text URLs and adds hyperlinks and detects preset smilies/emoticons from a function array.
function smilieMe($text) {
	$smiliesFind = [
	$smiliesReplace = [
		'<img src="images/smilies/smile.png" alt=":)" title=":)" loading="lazy"',
		'<img src="images/smilies/tongue.png" alt=":P" title=":P" loading="lazy"',
		'<img src="images/smilies/grin.png" alt=":D" title=":D" loading="lazy"',
		'<img src="images/smilies/confused.png" alt=":S" title=":S" loading="lazy"',
		'<img src="images/smilies/sad.png" alt=":(" title=":(" loading="lazy"',
		'<img src="images/smilies/proud.png" alt=":8" title=":8" loading="lazy"',
		'<img src="images/smilies/tea.gif" alt=":tea" title=":tea" loading="lazy"',
		'<img src="images/smilies/wow.png" alt=":o" title=":o" loading="lazy"',
		'<img src="images/smilies/wow.png" alt=":O" title=":O" loading="lazy"',
		'<img src="images/smilies/yay.png" alt=":q" title=":q" loading="lazy"',
		'<img src="images/smilies/yay.png" alt=":Q" title=":Q" loading="lazy"',
		'<img src="images/smilies/hug.gif" alt=":hug" title=":hug" loading="lazy"',
		'<img src="images/smilies/joy.gif" alt=":joy" title=":joy" loading="lazy"',
		'<img src="images/smilies/yes.gif" alt=":yes" title=":yes" loading="lazy"',
		'<img src="images/smilies/no.gif" alt=":no" title=":no" loading="lazy"'

    return preg_replace($smiliesFind, $smiliesReplace, $text);

function autopMe($content) {
	$content = trim($content);
	$content = stripslashes($content);

	 * temporarily replace two or more consecutive newlines
	 * into SOH characters (Start of Heading - first character of a message header)
	$content = preg_replace('~(\r\n|\n){2,}|$~', "\001", $content);

	// convert remaining single newlines into HTML <br>
	$content = nl2br($content);

	// replace SOH characters with paragraphs
	$content = preg_replace('/(.*?)\001/s', "<p>$1</p>\n", $content);

	$content = smilieMe($content);

	// parse URL addresses (ftp, http, https)
	$content = preg_replace('*(f|ht)tps?://[A-Za-z0-9\./?=\+&%]+*', '<a href="$0">$0</a>', $content);

	return $content;

As a bonus, the smilies are lazy loaded.

Related posts