I've done something similar with str_replace using this:
$string = $url;
$patterns = array();
$patterns[0] = 'searchforme';
$patterns[1] = 'searchforme1';
$patterns[2] = 'searchforme2';
$replacements = array();
$replacements[0] = 'replacewithme';
$replacements[1] = 'replacewithme1';
$replacements[2] = 'replacewithme2';
$searchReplace = str_replace($patterns, $replacements, $string);
How would I go about doing something similar with preg_replace?
I've built a very simple little css parser that searches for a specific tag within a comment wrapped around CSS properties, and replaces it with new data.
$stylesheet = file_get_contents('temp/'.$user.'/css/mobile.css');
$cssTag = 'bodybg';
$stylesheet = preg_replace("/(\/\*".$cssTag."\*\/).*?(\/\*\/".$cssTag."\*\/)/i", "\\1 background: $bg url(../images/bg.png) repeat-x; \\2", $stylesheet);
file_put_contents('temp/'.$user.'/css/mobile.css',''.$stylesheet.'');
I have multiple "cssTag"'s and they'll all need unique css to replace with (background, color, font-size etc) which is why I'm looking for a method like the str_replace one above.
preg_replace
can take an array just like str_replace
$string = 'I have a match1 and a match3, and here\'s a match2';
$find = ['/match1/', '/match2/'];
$replace = ['foo', 'bar'];
$result = preg_replace($find, $replace, $string);
You can also use T-Regx library
<?php
$stylesheet = file_get_contents('temp/'.$user.'/css/mobile.css');
$cssTag = 'bodybg';
$stylesheet = pattern("(/\*" . $cssTag . "\*/).*?(/\*/" . $cssTag . "\*/)", 'i')
->replace($stylesheet)
->all()
->by()
->map([
'searchforme' => 'replacewithme',
'searchforme1' => 'replacewithme2',
'searchforme1' => 'replacewithme2',
]);
You don't need delimiters /
, because T-Regx automatically adds them
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With