我正在尝试使用str_replace。当我使用array("","")
它工作并根据需要替换,但是当我使用预定义的数组时,在这种情况下从my_sql数据库获取它似乎工作。此外,str_replace
适用于preg_replace_callback()
<?
$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;
?>
我尝试过更改为mysqli_fetch_array并且没有做任何更改。 感谢。
答案 0 :(得分:1)
除非您使用$Starting_word
将$Finishing_word
和use
传递给回调函数,否则它们不在回调范围内
尝试
$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;