Janie
Janie

Reputation: 646

preg_replace by group in PHP

I have a string

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

And I want to replace like below

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

What I did is

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

I'm looking for a sort way like preg_replace. Any suggestion will be appreciated.

Upvotes: 2

Views: 556

Answers (2)

arkascha
arkascha

Reputation: 42984

I don't see any reason why a regular expression should make sense here. Instead I suggest you simply use the str_replace function in its ability to make multiple replacements at once:

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

The output obviously is:

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

This is a simple and robust approach and should be much more efficient than using regex based pattern matching.

Upvotes: 2

Jan
Jan

Reputation: 43199

In addition to my comment, you could use the following regex:

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

Upvotes: 3

Related Questions