1

I am trying to automatically format text to links in PHP but to trim long urls to a max character limit. And also remove 'http(s)' from outputted text.

blah blah http://example.com/some-long-slug-goes-here foo

should translate to:

blah blah <a href="http://example.com/some-long-slug-goes-here">example.com/some-long-sl...</a> foo (blah blah example.com/some-long-sl... foo)

Found a preg_replace solution here: How do I linkify urls in a string with php? but I'm incapable of editing it to my needs.

$string = preg_replace(
  "~[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]~",
  "<a href=\"\\0\">\\0</a>", 
  $string
);
pax
  • 482
  • 8
  • 26

1 Answers1

2

Create a capture group after the protocol:

$string = preg_replace(
  "~[[:alpha:]]+://([^<>[:space:]]+[[:alnum:]/])~",
  "<a href=\"\\0\">\\1</a>", 
  $string
);

then \1 will be the URL without the protocol. For the text limiting I'd recommend using CSS, Setting a max character length in css.

chris85
  • 23,846
  • 7
  • 34
  • 51
  • Thank you, this fixes it! :) Would it be possible to also remove the 'www.'? – pax Sep 29 '17 at 16:03
  • Yes, put the `www.` after the protocol but before the capture group, you also probably want that optional.. so update the beginning to `[[:alpha:]]+://(?:www\.)?` – chris85 Sep 29 '17 at 16:04