开发者

preg_replace not taking variables

开发者 https://www.devze.com 2022-12-18 02:24 出处:网络
$line = \"Hello World\"; $line= preg_replace(\"/Hello/\", $replacement, $line); - Works! $find = \"Hello\";
$line = "Hello World";

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

$find = "Hello";
$line= preg_replace("/开发者_JAVA技巧$find/", $replacement, $line); - Wont replace anything!

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

How can I use a variable in to tell preg_replace() what to find?


If you are literally using "Hello World", the examples should all work, and it would be really odd if they wouldn't.

If you are using different strings, with special characters, be sure to run a preg_quote on them before using them.


The error should be somewhere else. The following script works fine:

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

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

## output: Bye World

Can you provide more details. What is the value of $replacement?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号