It is not very clear to me if, when you find www.example.com/file, you want to replace all that piece, including the domain name, or just "/ file".
I will present a possible solution based on the first assumption. Anything you already tell me:
<?php
// Para la prueba
$url_image = 'https://www.ejemplo.com/archivo';
$image = 'www.foo.com/bar';
// Script
$variable='www.ejemplo.com/archivo';
$url_search='#^(https?://)'.preg_quote($variable, '#').'#i';
$result=preg_replace($url_search, '$1'.$image, $url_image);
print $result . "\n";
Changes made:
Most importantly, when incorporating the variable into the regular expression, escape it with preg_quote, since the variable can contain special characters with meaning for a regular expression (such as point .
for example)
I simplified the capture of http / s a bit by doing the optional 's' ( ?
)
I have changed the delimiters of the regular expression to #, this way I do not have to escape the bars and it is more readable.
When assigning the value to $variable
you have to encapsulate the string with quotes and end the instruction with ;
In str_replace you had the second and third parameters rotated. The second is the replacement expression and the third is the string where the substitutions are made.