0

I am Japanese web developer and I am not good at english , sorry.

$re_url = '/((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/i';

$string = preg_replace($re_url, '<a href="$1" target="_blank">$1</a>', $string);

In this way , you can add "a tag" to url in the string.

But when the url is like this ,

"http://xxxxx.xxxxx.co.jp/xxxxx/xxxxx/xxxxx.x.xxxxx?id=12345"

It doesn't work.

I think the get parameter(?id=12345) makes preg_replace confused.

Are there any idea to solve this problem?


Thank you so much for the answer.

What I want do is like this.

"Click here → http://xxxxx.xxxxx.co.jp/xxxxx/xxxxx/xxxxx.x.xxxxx?id=12345"

↓Change this string to

"Click here → <a href='http://xxxxx.xxxxx.co.jp/xxxxx/xxxxx/xxxxx.x.xxxxx?id=12345'>http://xxxxx.xxxxx.co.jp/xxxxx/xxxxx/xxxxx.x.xxxxx?id=12345</a>"

this.


I am so sorry. Now , I found out why this happens. My proper code is this.

$re_mail = '/((?:\w+\.?)*\w+@(?:\w+\.)+\w+)/i';
$re_tel = '/([0-9]{6,9,10,11}|[0-9-]{12,13})/i';
$re_br = '/\n|\r|(\r\n)/';
$re_url = '/((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/i';

$contents = preg_replace('#(script|about|applet|activex|chrome):#is', "\\1:", $contents);
$contents = preg_replace($re_mail, '<a href="mailto:$1">$1</a>', $contents);
$contents = preg_replace($re_tel, '<a href="tel:$1">$1</a>', $contents);
$contents = preg_replace($re_br, '<br/>', $contents);
$contents = preg_replace($re_url, '<a href="$1" target="_blank">$1</a>', $contents);

If I erase

$contents = preg_replace($re_mail, '<a href="mailto:$1">$1</a>', $contents);
$contents = preg_replace($re_tel, '<a href="tel:$1">$1</a>', $contents);
$contents = preg_replace($re_br, '<br/>', $contents);

these , link will be generated properly , but all of them are necessary. I don't want to erase these.

Kuru
  • 1,417
  • 2
  • 13
  • 20
  • The regex is correct, you can see the online test I made here https://www.phpliveregex.com/p/pps just change to `preg_replace` tab to see. So it actually works as expected so maybe your error is not in this part of the code? – Plamen Nikolov Sep 28 '18 at 11:34
  • Thank you so much. The problem was different. Please see my edit. – Kuru Sep 28 '18 at 12:02
  • Try to reorder the replacements like firstly try the `$re_url` and after that `$re_email`, `$re_tel`, `$re_br`, etc. – Plamen Nikolov Sep 28 '18 at 12:46

1 Answers1

1

I don't really know what you are trying to accomplish, but you could try to combine your regex with parse_url and use the "tagging" only on the part of the URL you are interested in.

In case you want to replace all the occurrences of URLs in a string with clickable links, see this answer.

Jan Richter
  • 1,976
  • 4
  • 29
  • 49