Php preg_replace_回调中的str_replace不工作。

Php preg_replace_回调中的str_replace不工作。,php,mysql,mysqli,str-replace,preg-replace-callback,Php,Mysql,Mysqli,Str Replace,Preg Replace Callback,我正在尝试用str_替换。当我使用数组(“,”)时,它会根据需要工作和替换,但是当我使用预定义数组时,在这种情况下,从my_sql数据库中获取的数组似乎不起作用。另外,str\u replace还可以与preg\u replace\u回调()之外的预定义数组一起工作。 我曾尝试更改为mysqli_fetch_数组,但没有更改。 谢谢。除非您使用use将$Starting\u word和$Finishing\u word传递给回调函数,否则它们在回调中不在范围内 试一试 $Starting_w

我正在尝试用str_替换。当我使用
数组(“,”)
时,它会根据需要工作和替换,但是当我使用预定义数组时,在这种情况下,从my_sql数据库中获取的数组似乎不起作用。另外,
str\u replace
还可以与
preg\u replace\u回调()之外的预定义数组一起工作。


我曾尝试更改为mysqli_fetch_数组,但没有更改。
谢谢。

除非您使用
use
$Starting\u word
$Finishing\u word
传递给回调函数,否则它们在回调中不在范围内

试一试

$Starting_word=array();
$Finishing_word=array();
$con=mysqli_connect(“localhost”、“root”、“root”、“Words”);
$getmodels=mysqli_query($con,“从单词中选择*);
而($res=mysqli\u fetch\u assoc($getmodels)){
$Starting_word[]=$res['1'];
$Finishing_word[]=$res['2'];
}
$string='我要替换的一些hello文本
一些我想替换的东西

”; $text\u to\u echo=preg\u replace\u回调(
"/()([^其中有一个已注释的
打印。\r
。它返回什么?PHP不知道或不关心数组来自何处,因此唯一的解释是,它包含的格式或数据与您之前尝试的硬编码数组不同,或者您之前的测试也不正确,正如@MarkBaker的回答所示。谢谢,这是有效的,但是n我尝试使用:file\u get\u contents来使用它,它似乎不会在整个文档中改变单词,而是在随机选择标记中。
<?
$Starting_word = array();
$Finishing_word = array();
$con = mysqli_connect("localhost","root","root","Words");
$getmodels = mysqli_query($con, "SELECT * FROM Words");
while($res = mysqli_fetch_assoc($getmodels)) {
$Starting_word[] = $res['1'];
$Finishing_word[] = $res['2'];
}
$string = '<html><h1> some hello  text i want to replace</h1><p>
some stuff i want to replace </p>';
$text_to_echo =  preg_replace_callback(
"/(<([^.]+)>)([^<]+)(<\\/\\2>)/s", 
function($matches){
    /*
     * Indexes of array:
     *    0 - full tag
     *    1 - open tag, for example <h1>
     *    2 - tag name h1
     *    3 - content
     *    4 - closing tag
     */
    //print_r($matches);
    $text = str_replace($Starting_word, $Finishing_word, $matches[3]);
    return $matches[1].$text.$matches[4];
}, 
$string
);
echo $text_to_echo;
?>
$Starting_word = array();
$Finishing_word = array();
$con = mysqli_connect("localhost","root","root","Words");
$getmodels = mysqli_query($con, "SELECT * FROM Words");
while($res = mysqli_fetch_assoc($getmodels)) {
    $Starting_word[] = $res['1'];
    $Finishing_word[] = $res['2'];
}
$string = '<html><h1> some hello  text i want to replace</h1><p>
some stuff i want to replace </p>';
$text_to_echo =  preg_replace_callback(
    "/(<([^.]+)>)([^<]+)(<\\/\\2>)/s", 
    function($matches) use ($Starting_word, $Finishing_word) {
        /*
         * Indexes of array:
         *    0 - full tag
         *    1 - open tag, for example <h1>
         *    2 - tag name h1
         *    3 - content
         *    4 - closing tag
         */
        //print_r($matches);
        $text = str_replace($Starting_word, $Finishing_word, $matches[3]);
        return $matches[1].$text.$matches[4];
    }, 
    $string
);
echo $text_to_echo;