Works:

$str = "http://element-bmw.ru/wp-content/uploads/2017/01/323e33885d8518e1eddecde0a54a18b7-702x336.jpg <br> http://element-bmw.ru/wp-content/uploads/2017/01/auto_parts_volkswagen_golf_3-768x450.jpg"; $str2 = preg_replace('/http:\/\/(.*?)\.(jpg|jpeg|png|gif|bmp)/i','//site.ru/misc/img.php?url=http://$1.$2',$str); echo '<pre>'.print_r([$str,$str2],TRUE).'</pre>'; 

Does not work:

 $str = "http://rambler.ru <br> http://element-bmw.ru/wp-content/uploads/2017/01/323e33885d8518e1eddecde0a54a18b7-702x336.jpg <br> http://element-bmw.ru/wp-content/uploads/2017/01/auto_parts_volkswagen_golf_3-768x450.jpg"; $str2 = preg_replace('/http:\/\/(.*?)\.(jpg|jpeg|png|gif|bmp)/i','//site.ru/misc/img.php?url=http://$1.$2',$str); echo '<pre>'.print_r([$str,$str2],TRUE).'</pre>'; 

With regulars on you, I count on your help.

  • What is the difference there? shall we break our eyes and try to find it ourselves? - teran
  • OK. the difference is that the whole line from the beginning of the first http to the first occurrence of the extension of the image falls into the regular calendar in the first case, this is just the first link (for it is in the picture). In the second case, these are two links in a row. - teran

1 answer 1

Obviously, the expression /http:\/\/(.*?)\.(jpg|jpeg|png|gif|bmp)/i will correspond to the line starting from the first http entry to the first one (jpg|jpeg|....) . It is caused by the fact that a mask (.*?) , which matches any character.

In your case (in the above), since the links are apparently separated by spaces, they should be excluded from all characters, that is, used, for example (\S*?) Or, if there is a tag in the separator, then you can also exclude the angle bracket ([^\s<]*?)

  • I can not figure out how to use. /http:\/\/([^\s<]?)\.(jpg|jpeg|png|gif|bmp)/i not working - borodatych
  • one
    @borodatych the asterisk is nowhere to go there. I really forgot to write it. - teran