6

I have a single regex and I want to replace each match in the array of matches with a corresponding array of replacements in the most efficient way possible.

So for instance, I have:

$string = '~~hello~~ there, how ~~are~~ ~~you~~?';

$pattern = '/~~(.*?)~~/';

$replacements = array();
$replacements[0] = 'hi';
$replacements[1] = 'am';
$replacements[2] = 'i';

and I want to turn $string into:

hi there, how am i?

Initially I hoped it'd be as simple as:

$string = preg_replace($pattern, $replacements, $string);

but it doesn't seem to work. So the first question is: if $replacements is an array, then does $string must also be an array?

Now, I can come up with (seemingly) inefficient ways to do this, like counting the number of matches and making an array filled with the appropriate number of identical regexes. But this leads us into question two: is there a more efficient way? How would you do it, PHP pros?

4

3 回答 3

3

你可以在这里使用一个简单的 eval 技巧:

print preg_replace('/~~(\w+)~~/e', 'array_shift($replacements)', $st);

array_shift将简单地从您的替换数组中获取第一个条目。

最好使用地图("hello" => "hi")。

于 2012-11-17T03:24:32.190 回答
1

我可能会使用preg_replace_callback

$string = '~~hello~~ there, how ~~are~~ ~~you~~?';

$pattern = '/~~(.*?)~~/'; 

var_dump(preg_replace_callback($pattern, 
    function($matches) { 
        static $replacements = array('hi', 'am', 'i'), $i = 0; 
        return $replacements[$i++ % count($replacements)]; 
    }, 
    $string));

输出:

string(19) "hi there, how am i?"
于 2012-11-17T03:38:19.117 回答
1

如果您要做的只是将这三个特定的短语换成另一组特定的短语,那么您可以使用str_replace它,因为它比preg_replace.

$subject = "~~hello~~ there, how ~~are~~ ~~you~~?";
$matches = array('~~hello~~', '~~are~~', '~~you~~');
$replace = array('hi', 'am', 'i');

str_replace($matches, $replace, $subject);
于 2012-11-17T05:59:09.620 回答