在 PHP 中按组preg_replace


preg_replace by group in PHP

我有一个字符串

$cmd = "java -jar yuicompressor-2.4.8.jar --type *file_type* *original_file* > *new_file*";

我想像下面这样替换

java -jar yuicompressor-2.4.8.jar --type css css/style.css > css/style.min.css

我所做的是

$cmd = str_replace("*original_file*", $v, $cmd);
$cmd = str_replace("*new_file*", "$k", $cmd);
$cmd = str_replace("*file_type*", "css", $cmd);

我正在寻找一种像preg_replace这样的排序方式.任何建议将不胜感激。

除了我的评论,您还可以使用以下正则表达式:

<?php
$cmd = "java -jar yuicompressor-2.4.8.jar --type *file_type* *original_file* > *new_file*";
$replacements = array(
    "file_type" => "something else",
    "original_file" => "original",
    "new_file" => "new");
$regex = '~'*([^*]+)'*~';
# look for a star literally
# capture everything that is not a star to group 1
# look for the closing star
$cmd = preg_replace_callback($regex,
    function($match) use($replacements) {
        return $replacements[$match[1]];
        # return the new value with match as key
    },
    $cmd);
echo $cmd;
// output: java -jar yuicompressor-2.4.8.jar --type something else original > new
?>

我看不出正则表达式在这里应该有意义的任何理由。相反,我建议您简单地使用 str_replace 函数,因为它能够一次进行多次替换:

<?php
$subject = 'java -jar yuicompressor-2.4.8.jar --type *file_type* *original_file* > *new_file*';
$catalog = [
  '*file_type*' => 'css',
  '*original_file*' => 'css/style.css',
  '*new_file*' => 'css/style.min.css'
];
var_dump(str_replace(array_keys($catalog), $catalog, $subject));

输出显然是:

string(78) "java -jar yuicompressor-2.4.8.jar --type css css/style.css > css/style.min.css"

这是一种简单而强大的方法,应该比使用基于正则表达式的模式匹配更有效。