There is a text of this type (the number of links in the line is from 0 to 10):

различный html текст с различными символами [url=http://img.site.kz/upload_image/000.JPG] [img=left]http://img.site.kz/upload_image/thumb/000.JPG[/img][/url] опять html код [url=http://img.site.kz/upload_image/111.JPG] [img=left]http://img.site.kz/upload_image/thumb/111.JPG[/img][/url] 

As a result, you need to get an array of this kind (so that it contains links from the code from the url tag):

 Array ( [0] => http://img.site.kz/upload_image/000.JPG [1] => http://img.site.kz/upload_image/111.JPG ) 

Or print the text that there are no links.

How to do this with a regular expression?

  • And what characters can be in the links? For example, links like http://localhost/?param[]=123 (or similar) may be present? And how then to determine that param[] is part of the link, not param[ and the closing bracket of the link? - BOPOH
  • The characters are just as in the example. The path to the picture in which the file name changes is - bullet2018

2 answers 2

 $str = "различный html текст с различными символами [url=http://img.site.kz/upload_image/000.JPG][img=left]http://img.site.kz/upload_image/thumb/000.JPG[/img][/url] опять html код [url=http://img.site.kz/upload_image/111.JPG][img=left]http://img.site.kz/upload_image/thumb/111.JPG[/img][/url] "; $pattern = '|(http://[a-zA-Z0-9_\./]+)|'; if (preg_match_all($pattern, $str, $matches , PREG_PATTERN_ORDER ) ) { $res= $matches[0]; print_r($res); } else { echo ("нет ссылок"); } 
  • And if the link will contain a question mark, or a closing square bracket? - BOPOH
  • $ pattern = '| (http: // [a-zA-Z0-9 _ \ ./?%] +) |'; And the symbol ']' in the links can not be present - sva
  • If you do not need links with [img = left], then: $ pattern = '| url = (http: // [a-zA-Z0-9 _ \ ./?%] +) |'; - sva
  • or $ pattern = '| [url = (\ w +? [^]] *]) |'; - sva
  • No links with [img = left], but | url = (http: // [a-zA-Z0-9 _ \ ./?%] +) | saves to the array also "url =" A | [[url = (\ w +? [^]] *]) | does not work - bullet2018

So my task was solved like this:

 $str = "различный html текст с различными символами [url=http://img.site.kz/upload_image/000.JPG][img=left]http://img.site.kz/upload_image/thumb/000.JPG[/img][/url] опять html код [url=http://img.site.kz/upload_image/111.JPG][img=left]http://img.site.kz/upload_image/thumb/111.JPG[/img][/url] "; $pattern = '|(?<=\[url=)[^\]]+|'; if (preg_match_all($pattern, $str, $matches , PREG_PATTERN_ORDER ) ) { $res= $matches[0]; print_r($res); } else { echo ("нет ссылок"); } 

And removed from the line extra links

 $str=preg_replace('#\[url=.*\[\/url\]#sUi', '', $str);