开发者

Write links in a natural and optimized way using JavaScript and/or PHP

开发者 https://www.devze.com 2023-03-23 15:22 出处:网络
The admin users of a module that I\'m developing want to add a functionality of automatically write links in the textarea(s) they fill.

The admin users of a module that I'm developing want to add a functionality of automatically write links in the textarea(s) they fill.

For example, if they write:

Please visit our page http://page.com

They want that http://page.com automatically is converted in a link:

<a href="http://page.com">http://page.com</a>

I want to do this in the best possible way in order of usability and performance.

I can't change the type of field (textarea) but I can do modifications with PHP and JavaScript that always is active (No Frameworks).

The users frequently edit the fields and the links are only important when they "publish" the forms, because the content of those 开发者_高级运维textarea(s) are displayed inside an HTML table.

A textarea input could have more than one link.

I appreciate your opinions and points of view to resolve this common situation.


In my opinion, you should handle this situation:

  • using PHP,
  • after reading the textarea contents from DB where it was stored,
  • before sending the HTML output

I don't know the details of your application context and its users, but when you output any user input as HTML, you must take care of security issues as XSS attacks, and others.

If $textarea_contents is the variable where the textarea contents are (read from the DB), I would apply the htmlspecialchars function first:

$output = htmlspecialchars( $textarea_contents );

After this, you can parse the output string or use a regular expression to transform the URLs in anchor elements. You choice depends on the level of precision you want. A couple of choices are:

  • http://code.iamcal.com/php/lib_autolink/lib_autolink.phps
  • http://jmrware.com/articles/2010/linkifyurl/linkify.html

And it is good to know this recommended reading about the complex problem of linkifying strings (from the creator of Stack Overflow website):

  • http://www.codinghorror.com/blog/2008/10/the-problem-with-urls.html

Good luck!


$code = preg_replace('/((https?|ftp):\/\/(?:[A-Z0-9-]+.)+[A-Z]{2,6}([\/?].+)?)/i','<a href="$1">$1</a>',$code);

(Regex Source)


This RegEx is better since take care of the parameters passed in the URL and finish when the URL finish and don't take spaces or other following words.

(https?|ftp)://([-A-Z0-9.]+)(/[-A-Z0-9+&@#/%=~_|!:,.;]*)?(\?[A-Z0-9+&@#/%=~_|!:,.;]*)?

Any other suggestion to face up this situation? Use JavaScript or PHP? Any idea?

0

精彩评论

暂无评论...
验证码 换一张
取 消