2010-01-27 53 views
0
$line = "Hello World"; 

$line= preg_replace("/Hello/", $replacement, $line); - Works! 

$find = "Hello"; 
$line= preg_replace("/$find/", $replacement, $line); - Wont replace anything! 

$string = "Hello"; 
$find = "/".$string."/"; 
$line= preg_replace($find, $replacement, $line); - Wont replace anything! 

如何使用变量来告知preg_replace()要查找什么?preg_replace不考虑变量

回答

0

如果你的字面意思是使用“Hello World”,那么这些例子应该都可以正常工作,如果他们不这样做,那将是非常奇怪的。

如果您使用不同的字符串和特殊字符,请务必在使用它们之前对其运行preg_quote

0

该错误应该在其他地方。以下脚本正常工作:

<?php 
$line = "Hello World"; 
$replacement = "Bye"; 

$string = "Hello"; 
$find = "/".$string."/"; 
print_r(preg_replace($find, $replacement, $line)); 

## output: Bye World 

您能否提供更多详细信息。 $replacement的价值是多少?