As many of you know by now, I’m developing an ajax driven chat room. I’m currently working out how to go about parsing posted links. there are 2 different formats, depending on whether or not someone wants to supply a title. Examples:
Dave: Check out my new web page at [link]http://www.geekcavecreations.com[/link].
Bill: Oh, yeah? I think [link=http://www.joecartoon.com]Joe Cartoon's Site[/link] is really cool, too!
The code I’m currently using is as follows:
function parseLinks($msg) {
global $lastFunction;
$lastFunction .= "_parseLinks";
if ((strpos($msg, "[link") === false) or ($_SESSION['linkFilter'] == "true")) return $msg;
$oldMsg = $msg;
$search1 = "[link]";
$search1a = "[link=";
$search1b = "]";
$search2 = "[/link]";
if (strpos($msg, $search1) !== false) {
$replStart = strpos($msg, $search1) + strlen($search1);
$replEnd = strpos($msg, $search2);
$replLen = $replEnd - $replStart;
$URL = substr($msg, $replStart, $replLen);
$msg1 = substr($msg,0,$replStart - strlen($search1));
$msg2 = substr($msg,$replEnd + strlen($search2));
$title = $URL;
$msg = $msg1 . '<a target="_blank" href="'.$URL.'">'.$title.'</a>'.$msg2;
}
else if (strpos($msg, $search1a) !== false) {
$replStart = strpos($msg, $search1a) + strlen($search1a);
$replEnd = strpos($msg, $search1b);
$replLen = $replEnd - $replStart;
$replTagEnd = strpos($msg, $search2);
$replTagLen = $replTagEnd - ($replEnd + 1);
$URL = substr($msg, $replStart, $replLen);
$title = substr($msg, $replEnd + 1, $replTagLen);
$msg1 = substr($msg,0,$replStart - strlen($search1a));
$msg2 = substr($msg,$replTagEnd + strlen($search2));
$msg = $msg1 . '<a target="_blank" href="'.$URL.'">'.$title.'</a>'.$msg2;
}
return $msg;
}
// end function parseLinks
I’m certain there’s a better way to do this using regular expressions, and I had thought the RegEx I saw earlier today seemed like it might have worked, but alas, no. What I have here seems to work, but there’s an awful lot of coding there to accomplish the job. I’m looking to streamline it, if possible. Any suggestions/tips/pointers?