4

How can I check if text in PHP contains a link in it's text? I have a database table format as follow.

+------------------+
| id | posts | tag |
+------------------+
| 1  | text 1|  0  | //no links
| 2  | text 2|  1  | //contains links

Basically, I want to verify that the submitted entry contains a link, if it does, the tag column will have a value of 1.

Can someone help me to properly code the above sample? Currently this is my PHP:

include 'function.php';

$text= $_POST['text'];

//if $text contains a url then do this function 
postEntryWithUrl($text);

//else here 
postEntry($text);
4
  • You can use Regular expression based search, look for URL regex on google. Oct 19, 2013 at 8:14
  • 3
    "Some people, when confronted with a problem, think 'I know, I'll use regular expressions.' Now they have two problems."
    – Tim
    Oct 19, 2013 at 8:15
  • If you ask about a string, ask a bout a string, not write long sentences about some database first. Keep Q&A to the concrete question, it's not here your support forum. Also take a look where this question has been asked before and answered. Then outline why the existing answers you have tried so far didn't make it to you. Until then I suggest to close to keep this site more straight to the point.
    – hakre
    Oct 19, 2013 at 8:38
  • sorry for that, i promise to keep that in mind. thanks.
    – bobbyjones
    Oct 19, 2013 at 8:43

2 Answers 2

13
$text = (string) $_POST['text'];

$bHasLink = strpos($text, 'http') !== false || strpos($text, 'www.') !== false;

if($bHasLink){
    postEntryWithUrl($text);
}else{
    postEntry($text);
}
5

You can use stristr()

$has_link = stristr($string, 'http://') ?: stristr($string, 'https://');

http://php.net/manual/en/function.stristr.php

Or preg_match()

preg_match('/(http|ftp|mailto)/', $string, $matches);
var_dump($matches);

https://www.php.net/manual/en/function.preg-match.php

8
  • 1
    What if there is no 'http://' but only 'www.' or neither?
    – user1316498
    Oct 19, 2013 at 8:18
  • 1
    I truthfully didn't notice I did that. Apologies.
    – user1316498
    Oct 19, 2013 at 8:20
  • 1
    @OraBrush no worries. Mine was just a guess, given the lack of context from the OP. Although he mentioned $text contains a url, I assume it's a fully qualified one. Certainly my answer doesn't work with SSL URL's though.
    – Mina
    Oct 19, 2013 at 8:21
  • 1
    what if i wrote only "google.com" ?
    – rushil
    Dec 13, 2016 at 6:20
  • 1
    This answer covers only 1 URL scheme, What if there's https infront or nothing like @rushil said. This answer should not be checked as answer...
    – strix25
    Aug 5, 2019 at 7:56

Not the answer you're looking for? Browse other questions tagged or ask your own question.