Cyril N.
Cyril N.

Reputation: 39859

How to replace a regex by given values in PHP?

I have a list of regular expressions like

$regex = "{Hello ([a-zA-Z]+), you are ([0-9]{2}) years old today\.}u"

Is there a function to do something like the following :

$result = function_i_am_looking($regex, "John", 25);
echo $result; // Outputs : "Hello John, you are 25 years old today."

Note: this is not some kind of templating engine I'm building ;)

Note 2: I can't predict what regex will be and in what order.

Upvotes: 0

Views: 55

Answers (4)

hek2mgl
hek2mgl

Reputation: 157992

Having the restriction that matching groups aren't nested in the regex patterns, you can use this:

$regex = "/Hello ([a-z]+), you are ([0-9]{2}) years old today./u";

$replacements=array("John", 25);
$result = preg_replace_callback('/\((.*?)\)/', function($m) use (&$replacements) {
        return array_shift($replacements);
}, $regex);

echo $result; // Outputs : "Hello John, you are 25 years old today."

IMO this is already the best - generic - thing you can do. However, while it works (a bit :) ), I don't think it is a good idea to do so. What you want is a template engine, or even printf (yes, you want that ;) )

Upvotes: 1

Toto
Toto

Reputation: 91415

How about:

$regex = "{Hello ([a-z]+), you are ([0-9]{2}) years old today.}u";
$result = function_i_am_looking($regex, "John", 25);
echo $result; 

function function_i_am_looking($reg, $str, $num) {
    $reg = preg_replace('/\(\[a-z\].*?\)/', '%s', $reg);
    $reg = preg_replace('/\(\[0-9\].*?\)/', '%d', $reg);
    return sprintf($reg, $str, $num);
}

Upvotes: 0

Satish Sharma
Satish Sharma

Reputation: 9635

you can use some mixed substring for replacing them

$your_string = "Hello @##@YOUR_NAME@##@, you are @##@YOUR_AGE@##@ years old today.";

$new_string = get_full_string($your_string, "John", 25);

echo $new_string;

function get_full_string($str, $name, $age)
{
     $str = str_replace("@##@YOUR_NAME@##@", $name, $str);
     $str = str_replace("@##@YOUR_AGE@##@", $age, $str);
     return $str;
}

LIVE DEMO

METHOD : 2

$your_string = "Hello ([a-z]+), you are ([0-9]{2}) years old today.";

$new_string = get_full_string($your_string, "John", 25);

echo $new_string;

function get_full_string($str, $name, $age)
{
     $str = str_replace("([a-z]+)", $name, $str);
     $str = str_replace("([0-9]{2})", $age, $str);
     return $str;
}

Demo

Upvotes: 0

idmean
idmean

Reputation: 14875

You maybe want to use sprintf()

sprintf("Hello %s, you are %d years old today.", "John", 25);

would print:

Hello John, you are 25 years old today.

Upvotes: 1

Related Questions