Wednesday, November 11, 2009

Rewrite URL to HTML with PHP

When presenting an article or other information it's convenient for readers to be able to click on links you are referring to. With regular expressions the composers are able to write clickable links without know any HTML.

In the example below we are getting the plain text in the variable $str.

Step one, which protocols are allowed? By adding more protocols to the array you're accepting them to be rewritten.
// Protocols
$protocols = array("http://", "https://", "ftp://");
// Imploding the array to fit the regex
$protocols = str_replace("/", "\/", implode("|", $protocols));

Step two, adding http:// to URLs without a specified protocol, like www.example.com
$str = preg_replace("/(?<=^|\(|\s)(www\.[A-Za-z0-9-_]+\.[A-Za-z\.]{2,6}(?:[\/\?].*)?)(?=[\.,!\?]*(?:\s|\(|\)|$))/U", "http://$1", $str);
Step three, replace all accepted URLs with HTML

$str = preg_replace("/(?<=^|\(|\s)({$protocols})((?:[A-Za-z0-9-_]+\.)?[A-Za-z0-9_-]+\.[A-Za-z\.]{2,6}(?:[\/\?].*)?)(?=[\.,!\?]*(?:\s|\(|\)|$))/U", "<a href=\"$1$2\">$2</a>", $str);
This code will work with the following ways to write URLs:
www.example.com
http://www.example.com
http://sub.example.com
http://example.com

www.example.com/example.html
www.example.com/exempe/
www.example.com?id=1
www.example.com/?id=1
www.example.com?id=1#23
www.example.com/example/#23

(http://example.com)
(example: www.example.com)
www.example.com/example)
www.example.com,
www.example.com?
www.example.com!
http://example.com. - The dot won't be a part of the link
http://example.com/. - The dot won't be a part of the link
www.example.com?id=id=123.43. - The last dot won't be a part of the link

But not with:
example.com
sub.example.com

Tuesday, November 10, 2009

Automatic XBMC library update

Since I have my computer set up to automatically download TV shows I wanted my XBMC library to be automatically updated at all time. The "Update on startup" option was insufficient in my case since I rarely restart my computer. The media center is running on Windows XP which meant Python was not an option (since it can't fully interact with XBMC under Windows). So I created a small VB application that uses the XBMC HTTP API to update the library:
Call UpdateXBMCLibrary()

Sub UpdateXBMCLibrary()
WScript.Timeout = 120
Dim objRequest
Dim URL

Set objRequest = CreateObject("Msxml2.ServerXMLHTTP")

URL = "http://localhost:8080/xbmcCmds/xbmcHttp?command=ExecBuiltIn&parameter=XBMC.updatelibrary(video)"

objRequest.open "GET", URL , false, "username", "password"
objRequest.Send

Set objRequest = Nothing
End Sub

I set up the web interface so that it runs on port 8080 with my desired username and password, used the Msxml2.ServerXMLHTTP object to make the HTTP request and voilĂ ! It works.

I added a scheduled task in order to make it update frequently. I guess you could modify the application so that it recognizes changes amongst the files but one update an hour works fine for me.