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.
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:
We hope you found this PHP tutorial useful to detect links in a text string.