2

I use this function to make links clickable:

function clickable($text) {
   $text = preg_replace("/(https?|ftps?|mailto):\/\/([-\w\p{L}\.]+)+(:\d+)?(\/([\w\p{L}#-;+-\/_\.]*(\?\S+)?)?)?/u", '<a target="_blank" href="$0">$0</a>', $text);
   return $text;
}

It works fine but there is one little problem. If the $text variable contains a string like this:

http://example.com

some text

i.e. link, line break(s) and some text, I get incorrect result. Instead of this:

<a target="_blank" href="http://example.com">http://example.com</a>

it becomes:

<a target="_blank" href="http://example.com<br">http://example.com</a>
/>

some text

Here is how I display text on my site:

<?php echo clickable(nl2br($db['content'])); ?>

nl2br function converts all line breaks into html <br /> tags but this function thinks it should keep this tag in url...

Hope I'm clear :)

Any ideas?

1
  • You have a character class with [#-;+-\\] - is this intentional? For one, [#-;] contains [+-\\], which is weird. Commented Aug 22, 2010 at 11:33

1 Answer 1

2

At the end of your pattern you have \S+ - this allows all non-space characters, including <, and the reason your regex doesn't work as expected. I'm not quite sure what is the role of that part, consider removing the (\?\S+)? and see if it's working for you.

Another option is changing that group to: [^\s<]* - this will not capture spaces and the < sign, solving exactly this problem...

Sign up to request clarification or add additional context in comments.

2 Comments

No, that doesn't seem to be a good solution... If I remove this part and there are some special symbols in utl, for example ? or - only the part before that symbols is shown as url.
@Levani - I just explained what is causing your error - I've updated my answer with a possible solution. Note that \S is quite a strong selector... Anyway, I simplified (\?\S+)? into [^\s<]* - it contains \ anyway, and * seems more appropriate here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.