Web development and examples of PHP, jQuery, HTML5, WordPress, MySQL & AMP

How to detect links in a text string with PHP

Let’s see how to detect links and links in a text string with PHP using a simple script. In the analyzed strings we will have links with www, http://, https://, twitter hashtag and twitter profiles.

PHP is a very powerful language with which we can manipulate, format and operate with text strings very easily.

Example code to detect links in a string with PHP preg_replace()

In the following example you can see working the code placed under these lines. The function used for detection and replacement is PHP preg_replace().

The string we are going to have is the following: http://www.anerbarrena.com https://www.facebook.com www.google.es @anerbarrena #anerbarrena.

This is the source code of the demo to detect the links:

Let’s review the source code:

  1. Line 2: In $original string we set de links to filter.
  2. Líneas 8 y 10: Detect in the string normal links as http, https or www. Then we add the link code.
  3. Línea 14: We look for the word to contain a @.
  4. Línea 15: We look for the word to contain a #.

We hope you found this PHP tutorial useful to detect links in a text string.

Cookie Policy

This website uses cookies to provide you with the best user experience. If you continue to browsing you are consenting to the acceptance of these cookies and acceptance of our cookie policy, click the link for more information.

Aviso de cookies