在PHP中按组分组preg_replace

时间:2016-02-10 07:57:53

标签: php regex preg-replace

我有一个字符串

$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这样的排序方式。任何建议将不胜感激。

2 个答案:

答案 0 :(得分:3)

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

<?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
?>

答案 1 :(得分:2)

我认为正则表达式在这里没有任何理由。相反,我建议您只需使用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"

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