It is necessary for a well-known link to get the absolute path to the file on the server. I implement it as follows:

$image = preg_replace("/^http.*/{2}[^/]*/i", $_SERVER[DOCUMENT_ROOT], "http://example.com/image.jpg"); 

When executing this code, $image takes the value null , although in theory there should be a full path to the file. preg_last_error says that no errors have occurred. I do not even know what could be wrong in one line of code ...

  • Your regular address at example.com/folder//image.jpg will lead to a bad result. . * captures the entire text to the end of the line, then goes back to the first // from the end of the line, and [^ \ /] * captures everything to image.jpg - ReinRaus

1 answer 1

It is necessary to escape slashes if you use a slash as a separator.
Instead of a point it is better to put a colon. A dot is any character.
This is how it works.

 $image = preg_replace("/^https?:\/\/[^\/]*/i", $_SERVER[DOCUMENT_ROOT], "http://example.com/image.jpg"); 
  • in this case it would be better to use another separator) The regular is better read) - Alex Kapustin pm
  • @shurik, it seems to me a matter of habit. I always use slashes, for example, and when I see delimiters! @ # {} In someone else's regulars, they first make me stupor for 5 seconds :) - ReinRaus
  • Thanks It works. And the need to escape slashes is a php feature? Or does all regular expressions apply? I also for some reason thought that if something was wrong with the regular preg_last_error , then preg_last_error should return an error. - co11ter