preg_replace PHP 组

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"

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