*new_file*"; -6ren">
gpt4 book ai didi

php - PHP中的preg_replace按组

转载 作者:行者123 更新时间:2023-12-04 15:14:03 25 4
gpt4 key购买 nike

我有一个字符串

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

关于php - PHP中的preg_replace按组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35309639/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com