Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP find all links in the text

Tags:

regex

php

I want to find all links in the text like this:

Test text http://hello.world Test text 
http://google.com/file.jpg Test text https://hell.o.wor.ld/test?qwe=qwe Test text 
test text http://test.test/test

I know i need to use preg_match_all, but have only idea in the head: start search from http|https|ftp and end search where space or end of the text appears, thats all i need really, so all links wiil be found properly.

Anyone can help me with php regexp pattern?

I think i need to use assertions in the end of pattern, but can`t understand their properly usage for now.

Any ideas? Thanx!

like image 349
swamprunner7 Avatar asked Apr 29 '14 13:04

swamprunner7


People also ask

How to find link from text in PHP?

Using built-in PHP function preg_replace(), we can easily find the URLs in text and make links in PHP. The preg_replace() function matches the pattern from string and replaces it with a defined modified string. You can also check Find URLs in string and make a link using JavaScript.


1 Answers

I'd go with something simple like ~[a-z]+://\S+~i

  • starts with protocol [a-z]+://
  • \S+ followed by one or more non-whitespaces where \S is a shorthand for [^ \t\r\n\f]
  • used modifier i (PCRE_CASELESS) (possibly not really necessery)

So it could look like this:

$pattern = '~[a-z]+://\S+~';

$str = 'Test text http://hello.world Test text 
http://google.com/file.jpg Test text https://hell.o.wor.ld/test?qwe=qwe Test text 
test text http://test.test/test';

if($num_found = preg_match_all($pattern, $str, $out))
{
  echo "FOUND ".$num_found." LINKS:\n";
  print_r($out[0]);
}

outputs:

FOUND 4 LINKS:
Array
(
    [0] => http://hello.world
    [1] => http://google.com/file.jpg
    [2] => https://hell.o.wor.ld/test?qwe=qwe
    [3] => http://test.test/test
)

Test on eval.in

like image 144
Jonny 5 Avatar answered Nov 02 '22 21:11

Jonny 5