Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

performing multiple preg_replace with different search & replace each time

Tags:

css

php

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.

like image 767
tctc91 Avatar asked Feb 07 '12 16:02

tctc91


2 Answers

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);
like image 71
Joe Avatar answered Oct 25 '22 05:10

Joe


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

like image 42
Danon Avatar answered Oct 25 '22 05:10

Danon