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>
- onewhen should it be transformed? during input, after it, after the form has been sent? - zhenyab
|
1 answer
Yes, there are thousands of such "converters", only there is not one that would 100% recognize everything and correctly :-) The most general considerations:
- It is not necessary to take a line without a protocol, there will be a lot of false "links"
- 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
- 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):
^http:\/\/[a-z_\-0-9]{2,}\.[az]{2,6}\/?\S*$
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
|