用 preg_replace() 替换的确切字符串

Exact string replacing with preg_replace()

我在尝试替换此字符串时遇到问题:

str1 = "mysql_connect($dbhost.':'.$dbport, $dbusername, $dbuserpass);";

使用其他字符串:

str2 = "$con = mysqli_connect($dbhost,$dbusername,$dbuserpass,"normativa",$dbport);";

我试过用这个:

$text = str_ireplace($str1,$str2,$text);

问题似乎出在 . (点)在第一个字符串中。我试着用“。”转义它。但没有运气。

是否有任何其他的点转义方法或另一个 php 函数来完成同样的事情?

您正在使用双引号,它将每个 $ 作为变量。 试试这个:

$text = str_replace('mysql_connect($dbhost.\':\'.$dbport, $dbusername, $dbuserpass);','$con = mysqli_connect($dbhost,$dbusername,$dbuserpass,"normativa",$dbport);', $text);