2010-01-27 52 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的價值是多少?