Question

I'm working on a PHP dynamic web page that has a <textarea> element that lets user write text and have it show in "real time" in a <div> element, just JavaScript-processing the text and tags.

I change the "b", "u", and tags between brackets (like phpBB style) to their HTML equivalents like "strong", "u", and so on using JavaScript regexps.

Problem occurs when I need to process the url tag, where I need to extract the URL from input that looks something like this:

[url=http://...]

How can I replace that with:

<a href="http://...">
Was it helpful?

Solution

This should work:

str.replace(/\[url=([^\s"<>\]]+)\]/gi, '<a href="$1">$1</a>');

That should take the parameters in [url=...] and, barring any funny business (<, > or spaces), change it to a hyperlink, using the URL as both the destination and the link text.

This will allow things like [url=javascript:while(1)alert('Boo!')], which will produce a link that, when clicked, will really annoy the user - you'll have to add some sanitisation filtering to block stuff like that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top