Qhiliqq
Qhiliqq

Reputation: 83

PHP replace string with file_get_contents

I'm trying to replace a string in a file, so far so good. The file is a htm file in html format bt this shouldn't be a problem.

My script looks like this:

$file = './test.htm';
$content = file_get_contents($file);
$str = str_replace('Signature','Test',$content);
file_put_contents('./test2.htm', $str);

The problem is str_replace doesn't replace the string "Signature", the output file has exactly the same content as my input file.

If I use the file content without file_get_contetnts, just while defining the string as a variable, my script works like a charme.

Upvotes: 0

Views: 325

Answers (2)

Qhiliqq
Qhiliqq

Reputation: 83

With help from @MB-abb I found out that the encoding is UCS-2 LE BOM.

The added line in my script is now:

$str = mb_convert_encoding($str, "UTF-8", "UCS-2LE");

Which changes UCS-2LE to UTF-8. Now str_replace works like a charme.

Thanks!

Upvotes: 2

Debuqer
Debuqer

Reputation: 395

Your code looks fine.

  1. Make sure you have actually 'Signature' in your code.
  2. Make sure you don't use any non-printable unicode characters with Signature.
  3. Append 'Signature' at the end of your test.htm and see if your code works.

Edited:

  1. Make sure your file use a valid and supported encoding( like UTF-8 )

Upvotes: 2

Related Questions