Search http or https with a regular expression and within that expression you can place a PHP variable

0

If someone could help me, I'm not very good with regular expressions, this is what I have so far:

$variable=www.ejemplo.com/archivo

$url_search='^(http:\/\/|https:\/\/)?'.$variable;

url_search: Lo uso para buscar y reemplazar dentro de str_replace...

$result=str_replace($url_search, $url_image, $image);

Thank you very much

    
asked by Omar32 09.07.2018 в 20:35
source

1 answer

0

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.
  • answered by 14.07.2018 в 01:08