php - preg_replace with multiple patterns replacements at once -


i have few substitutions apply on $subject don't want allow output old substitutions #(1 .. i-1) match current substitution #i.

$subject1 = preg_replace($pat0, $rep0, $subject0); $subject2 = preg_replace($pat1, $rep1, $subject1); $subject3 = preg_replace($pat2, $rep2, $subject2); 

i tried using 1 preg_replace arrays patterns , replacement hoping make @ once; turned out not more calling simple preg_replace successively (with optimization of course)

after read preg_replace_callback, guess not solution.

any help?

use callback, can detect pattern matched using capturing groups, (?:(patternt1)|(pattern2)|(etc), matching patterns capturing group(s) defined.

the problem current capturing groups shifted. fix (read workaround) use named groups. (a branch reset (?|(foo)|(bar)) work (if supported in version), you'd have detect pattern has matched using other way.)

example

function replace_callback($matches){     if(isset($matches["m1"])){         return "foo";     }     if(isset($matches["m2"])){         return "bar";     }     if(isset($matches["m3"])){         return "baz";     }     return "something wrong ;)"; }  $re = "/(?|(?:regex1)(?<m1>)|(?:reg(\\s*)ex|2)(?<m2>)|(?:(back refs) work intended \\1)(?<m3>))/";  $rep_string = preg_replace_callback($re, "replace_callback", $string); 

not tested (don't have php here), work.


Comments

Popular posts from this blog

c++ - Is it possible to compile a VST on linux? -

java - Output of Eclipse is rubbish -

jquery - Confused with JSON data and normal data in Django ajax request -