Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
449 views
in Technique[技术] by (71.8m points)

php - performing multiple preg_replace with different search & replace each time

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...