Hello! How to convert a regular url to an active link? There is a text entry field, it is necessary that the URL of the page type https://ru.stackoverflow.com/questions/tagged/php/ is converted to <a href="https://ru.stackoverflow.com/questions/tagged/php/" target="_blank">https://ru.stackoverflow.com/questions/tagged/php/</a>

  • one
    when should it be transformed? during input, after it, after the form has been sent? - zhenyab

1 answer 1

Yes, there are thousands of such "converters", only there is not one that would 100% recognize everything and correctly :-) The most general considerations:

  1. It is not necessary to take a line without a protocol, there will be a lot of false "links"
  2. After the protocol (we are talking only about http (s) and ftp, for example, we don’t touch any exotic) at least two alphanumeric characters, followed by a full stop and another 2 to 6 letters (we don’t touch national domains) zafigachit check on the whole list TLD
  3. And then creativity begins :) Suppose we do not check the port, omit the query string, hashes too. Anyway, the problem of the last character remains (that is, if something ends in a dot, comma, bracket, etc. - will we consider this part of the URL?) ... And so on.

In general, the most stupid basic variant from which you can dance further (schematically):


Where instead of the last \ S * should be creativity. (and this is not bothered with the fact that between the protocol and the TLD). Here, for example, how people are perverted ...

You can also look at the source code of various forums to see who has done it, look for functions / methods with names like make_clickable or something like that.

Or here is an example from FormValidator :: Lite :: Constraint :: URL :

 rule 'HTTP_URL' => sub { $_ =~ /^s?https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#]+$/ }; 
  • Thank! I will create :) - noob_pro