PHP & MySQL

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:

//original string with no detected links
$original_string= 'http://www.anerbarrena.com https://www.facebook.com www.google.es @anerbarrena #anerbarrena';
echo $original_string;


//Filtered string with normal links
//filter for normal links
$final_string= preg_replace("/((http|https|www)[^\s]+)/", '<a href="$1">$0</a>', $original_string);
//detect if links dont have https
$final_string= preg_replace("/href=\"www/", 'href="https://www', $final_string);
echo $final_string;

 
//Filtered string with normal and Twitter format links
//get twitter format links
$final_string = preg_replace("/(@[^\s]+)/", '<a target=\"_blank\"  href="http://twitter.com/intent/user?screen_name=$1">$0</a>', $final_string);
$final_string = preg_replace("/(#[^\s]+)/", '<a target=\"_blank\"  href="http://twitter.com/search?q=$1">$0</a>', $final_string);
echo $final_string;

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.

Share
Published by
Aner Barrena