Start New Discussion within our Web Development Community

Hi I have been using a replace array which has worked wonders but now I have just added one and it wont work why is this please. I can understand why it wont work but do not know what i have to do to sort it. I added the last one to replace a ' with a -

$old = array(' ', '/', 'amp;', ''');
$new = array('-', '-', '-', '-');

Thanks for your help.

Change the wrapping quotes to double quotes:

$old = array(' ', '/', 'amp;', "'");

Or escape the quote:

$old = array(' ', '/', 'amp;', '\'');

and it should work.

Can you provide some code? Here's my test:


$string = "Hello we're checking &amp; testing this brand-new /string/";

$old = array(' ', '/', 'amp;', "'");
$new = array('-', '-', '-', '-');

$string = str_replace($old, $new, $string);
$string = implode('-', array_filter(explode('-',$string)));
echo $string;
echo PHP_EOL;

Outputs: Hello-we-re-checking-&-testing-this-brand-new-string

It works also without $new array, since the character to replace is the same for all:

echo str_replace($old, '-', $string);
This article has been dead for over six months. Start a new discussion instead.