views:

18

answers:

2
$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!

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

A: 

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.

Pekka
A: 

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?

Ivan Nevostruev