每次使用不同的搜索和替换执行多个preg_replace

2022-08-30 21:40:24

我用这个对str_replace做了类似的事情:

$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);

我该如何用preg_replace做类似的事情?

我构建了一个非常简单的小css解析器,它可以在围绕CSS属性的注释中搜索特定标记,并将其替换为新数据。

$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.'');

我有多个“cssTag”,它们都需要唯一的css来替换(背景,颜色,字体大小等),这就是为什么我正在寻找一种像上面str_replace一样的方法。


答案 1

preg_replace可以像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);

答案 2

您还可以使用 T-Regx 库

<?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',
    ]);

您不需要分隔符,因为T-Regx会自动添加它们/


推荐