PHP substr_replace encoding

I want to write to a text file. When I use substr_replace in php, the encoding changes. It does not print Greek characters correctly. If I'm not all right. Any suggestions?

<?php $file = "test.txt"; $writeFile = fopen($file, "w+");//read/write $myarray = array("δφδφ","δφδσφδσ","δφδφδ"); $myarray[0] = substr_replace($myarray[0],"ε", 0,1); foreach ($myarray as $data){ fwrite($writeFile, $data."\n"); } ?> 

RESULT
εφδφ
δφδσφδσ
δφδφδ

RESULTS WITH NO substr_replace
δφδφ
δφδσφδσ
δφδφδ

+6
source share
5 answers

You can use these two functions:

from shkspr.mobi

 function mb_substr_replace($original, $replacement, $position, $length) { $startString = mb_substr($original, 0, $position, "UTF-8"); $endString = mb_substr($original, $position + $length, mb_strlen($original), "UTF-8"); $out = $startString . $replacement . $endString; return $out; } 

From github

 function mb_substr_replace($str, $repl, $start, $length = null) { preg_match_all('/./us', $str, $ar); preg_match_all('/./us', $repl, $rar); $length = is_int($length) ? $length : utf8_strlen($str); array_splice($ar[0], $start, $length, $rar[0]); return implode($ar[0]); } 

I tried both and both work well

+5
source

Assuming you encode the Greek language in multibyte encoding (e.g. UTF-8), this will not work because the main functions of the PHP string, including substr_replace , are not multibyte. They process one character equal to one byte, which means that you will finish splitting multibyte characters in half if you replace only your first byte. You need to use a more manual approach, including a multibyte known string function such as mb_substr :

 mb_internal_encoding('UTF-8'); echo 'ε' . mb_substr('δφδφ', 1); 

Comments @arma links in the comments wrap this functionality in function.

+3
source

Try this version:

 function mb_substr_replace ($string, $replacement, $start, $length = 0) { if (is_array($string)) { foreach ($string as $i => $val) { $repl = is_array ($replacement) ? $replacement[$i] : $replacement; $st = is_array ($start) ? $start[$i] : $start; $len = is_array ($length) ? $length[$i] : $length; $string[$i] = mb_substr_replace ($val, $repl, $st, $len); } return $string; } $result = mb_substr ($string, 0, $start, 'UTF-8'); $result .= $replacement; if ($length > 0) { $result .= mb_substr ($string, ($start+$length+1), mb_strlen($string, 'UTF-8'), 'UTF-8'); } return $result; } 
+3
source

You can try using the mb_convert_encoding() function to set the correct encoding.

0
source
 function replace($string, $replacement, $start, $length = 0) { $result = mb_substr ($string, 0, $start, 'UTF-8'); $result .= $replacement; if ($length > 0) { $result .= mb_substr($string, ($start + $length), null, 'UTF-8'); } return $result; } 
0
source

Source: https://habr.com/ru/post/919213/


All Articles