Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/247.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP中的preg_替换为group_Php_Regex_Preg Replace - Fatal编程技术网

PHP中的preg_替换为group

PHP中的preg_替换为group,php,regex,preg-replace,Php,Regex,Preg Replace,我有一根绳子 $cmd=“java-jar yuicompressor-2.4.8.jar--type*文件类型**原始文件*>*新文件*” 我想替换如下所示 java-jar yuicompressor-2.4.8.jar——键入css/style.css>css/style.min.css 我所做的是 $cmd = str_replace("*original_file*", $v, $cmd); $cmd = str_replace("*new_file*", "$k", $cmd); $

我有一根绳子

$cmd=“java-jar yuicompressor-2.4.8.jar--type*文件类型**原始文件*>*新文件*”

我想替换如下所示

java-jar yuicompressor-2.4.8.jar——键入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\u 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));

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

preg\u replace\u回调使用regex
\*[^*]+\*
将帮助您解决问题,请参阅
string(78) "java -jar yuicompressor-2.4.8.jar --type css css/style.css > css/style.min.css"