Calling a function from within preg_replace

RustyRazorblade Consulting RustyRazorblade Consulting
1 min read

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.

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.

RustyRazorblade Consulting

RustyRazorblade Consulting

Apache Cassandra Consultant and Distributed Systems Expert

Related Posts

Need Expert Help with Apache Cassandra?

Get professional consulting for your distributed systems challenges. Performance optimization, architecture design, and troubleshooting.