A
A
alexragulin2019-04-21 20:26:30
PHP
alexragulin, 2019-04-21 20:26:30

A clickable link in the text, with long links trimmed?

Good afternoon!
I broke my whole head with a seemingly simple regex

function linkes($text){
  return preg_replace("/(^|[\n ])([\w]*?)((ht|f)tp(s)?:\/\/[\w]+[^ \"\n\r\t<,]*)/is", "$1$2<a target=\"_blank\" href=\"$3\" >$3</a>", $text);
  }

It works well, but with long links, the layout crumbles and the webmaster starts to swear on the page, for not being adaptive, help cut $3 to 40 characters
Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
dodo512, 2019-04-23
@alexragulin

https://regex101.com/r/uBNCQb/1

function linkes($text){
  return preg_replace('~((ht|f)tps?://\w[^\s"<,]{0,30})[^\s"<,]*~i', '<a target="_blank" href="$0" >$1</a>', $text);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question