substr_replace encoding in PHP

戏子无情 提交于 2019-12-04 06:21:40

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

Assuming you're encoding the Greek in a multi-byte encoding (like UTF-8), this won't work because the core PHP string functions, including substr_replace, are not multi-byte aware. They treat one character as equal to one byte, which means you'll end up slicing multi-byte characters in half if you only replace their first byte. You need to use a more manual approach involving a multi-byte aware string function like mb_substr:

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

The comment @arma links to in the comments wraps that functionality in a function.

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;
}
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;
}
user1474090

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!