如何用PHP中的给定值替换正则表达式?

时间:2014-08-07 11:59:46

标签: php regex

我有一个正则表达式列表,如

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

是否有功能可以执行以下操作:

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

注意:这不是我构建的某种模板引擎;)

注意2:我无法预测正则表达式的位置和顺序。

4 个答案:

答案 0 :(得分:1)

您可能想要使用sprintf()

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

会打印:

Hello John, you are 25 years old today.

答案 1 :(得分:1)

具有匹配组未嵌套在正则表达式模式中的限制,您可以使用:

$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这已经是最好的 - 通用 - 你可以做的事情。然而,虽然它有效(有点:)),但我不认为这样做是个好主意。你想要的是一个模板引擎,甚至是printf(是的,你想要那个;))

答案 2 :(得分:0)

您可以使用一些混合子字符串来替换它们

$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

方法: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

答案 3 :(得分:0)

怎么样:

$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);
}