0

I use this preg_replace to change text urls to clickable in my script: Replacing Text link as link with preg_replace

yesterday I tested my script and these preg_replace doesn't work fine.

Here is example:

(...) stronie  http://tpn.pl/nowosci/uwaga-skiturowcy-1).

And these preg_replace finally create this:

stronie <a href="http://tpn.pl/nowosci/uwaga-skiturowcy-1)." target="_blank">tpn.pl</a>

Why this preg_replace added ")." at the end of an URL? How to accept only "A-Z, a-z, 0-9, /" at the end of an URL string (I think I wrote everything accept ends of url ?)?

Thanks.

EDIT:

Here is my code:

$sub_message = preg_replace('|([\w\d]*)\s?(https?://([\d\w\.-]+\.[\w\.]{2,6})[^\s\]\[\<\>]*/?)|i', '$1 <a target="_blank" href="$2">$3</a>', $value['description']);
$sub_message = trim(str_replace("\n", "<br />", $sub_message));
9
  • Post your code, we don't want to guess it. Commented Mar 7, 2016 at 19:04
  • I added my code, sorry, I forgot. Commented Mar 7, 2016 at 19:05
  • Take a look at this regex101.com/r/mS9dT2/1 I added a capturing group, now you can see why you also get ").". Commented Mar 7, 2016 at 19:07
  • This regex also get ). at the end of an URL string. Commented Mar 7, 2016 at 19:08
  • I know, now take a close look at the link and you'll see why. Commented Mar 7, 2016 at 19:09

1 Answer 1

1

You can use the following code to change urls to links in a string :

<?php

$x="foobar http://example.com foobar";
echo preg_replace("~(https?://(?:www\.)?[^\s]+)~i","<a href='$1'>$1</a>",$x);

Online demo : https://eval.in/532195

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

1 Comment

AS text, I wolud like to have only domain name so it should get as result: foobar <a href="http://example.com">example.com</a> foobar

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.