Calling a function from within preg_replace

October 12, 2006 – 11:58 am

Regular expressions are awesome. However, sometimes doing everything in them is extremely difficult, or impossible. Luckily, we can flex the power of preg_replace’s ‘e’ option to execute the replacement string as PHP code.

The reason why I found this is was I was looking for a suitable URL auto-linker that could shorten the url to a certain length. I found several examples on PHP.net, but unfortunately none of them did a good job of shortening the URL, or formatting it in a special way. This particular example is a simplified version of my auto-linker.

Consider this code:

function URL_Link( $txt)
{
	$replacement = "'<a xhref=\"\\1\">' . GetHost(\"\\1\") . '</a>'";
	$txt = preg_replace( "/((http|ftp)+(s)?:\/\/[^<>\s\)\]]+)/ie",
					$replacement , $txt );
	return $txt;
}

function GetHost($url)
{
	$arr = parse_url( $url );
	$result = $arr['scheme'] . "://" . $arr['host'];
	return $result;
}


The text of the replacement can include functions which can be passed the preg matches. Calling URL_Link will auto link all the urls in a block of text.

These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Reddit

Post a Comment