带有file_get_contents的preg_replace

时间:2013-02-03 11:42:29

标签: php function preg-replace file-get-contents

我在这里查看了几个问题,并进行了谷歌搜索,但我似乎找不到正确的方法来做这件事。

我正在使用此功能

function replace_c($content){
    global $db;
    $replacements = $db->query("SELECT * FROM `replacements`");
    while($replace = $replacements->fetch_assoc()){
        preg_replace("/".$replace['triggers']."/i",$replace['php'], $content);
    }
    return $content;
}

这是我对函数的调用

$contents = replace_c(file_get_contents("templates/" . $settings['theme'] . "/header.html"));

它没有给出错误,它只是不会像它应该替换文本所以我不确定该函数是否实际工作。我确实试过了preg_replace_callback,但我不认为我完全理解它是如何工作的,除了错误之外什么都没有产生,我是否必须采用回调路线,或者我只是在当前函数中遗漏了什么?

3 个答案:

答案 0 :(得分:2)

您永远不会将preg_replace的返回值分配给$content ....您需要的是:

$content = preg_replace("/".$replace['triggers']."/i",$replace['php'], $content);

答案 1 :(得分:2)

基拉,

preg_Replace函数返回替换的字符串。您发布到它的$ content主题不会作为参考更新。所以尝试将代码更改为;

$content = preg_replace("/".$replace['triggers']."/i",$replace['php'], $content);

答案 2 :(得分:1)

您需要将替换的内容存储回变量。

$content = preg_replace(...);

另外,你确定str_replace()还不够吗?