Blog
Regexp string replace with PHP XSL
2009-03-19 13:26:52 by Martynas Jusevičius
While XSLT 2.0 has regular expression support, it is missing in XSLT 1.0. Tasks like string pattern matching and replace cannot be done in native XSLT 1.0 code, extension functions are needed for that. Luckily, it can be achieved with PHP XSL in the same fashion as URL-encoding, by registering PHP function support on XSLT processor and calling native PHP functions as XPath functions in PHP namespace.
One of the common cases for this functionality when using XSLT as View templates would be replacement of http:// links in text (for example, message content from a database) with actual <a> hyperlink elements. Here is a quick-and-dirty PHP function that does that:
abstract class FrontEndView extends XSLTView
{
// ...
public static function replaceLinks($text)
{
$text = htmlspecialchars($text);
$text = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]", "<a href=\"\\0\">\\0</a>", $text);
$text = "<div xmlns=\"http://www.w3.org/1999/xhtml\">".$text."</div>";
$doc = new DOMDocument();
$doc->loadXML($text);
return $doc->documentElement;
}
}It replaces link text with hyperlinks at string level, then loads it to a DOM document and returns it. Before it can be accessed from a stylesheet, registerPhpFunctions() needs to be called on the XSLT processor instance.
The XSLT code then looks like this:
<xsl:copy-of select="php:function('FrontEndView::replaceLinks', string($text))/node()"/>
Notice that while you have to send string content to the function, what you get back is a node list, because the replaced text becomes XML elements, which are mixed with the unreplaced text nodes.
Don't forget to register the PHP namespace (http://php.net/xsl) in your stylesheet and use exclude-result-prefixes="php" for it not to appear in the result document.
I guess similar functions could be used to implement BBCode or wiki syntax support.
Comments (2)
Yeah, sure hope to see xslt 2.0 included with PHP
great
great code

2009-03-19 15:21:26 by David