【问题标题】:substr_replace function returns weird symbols along with the stringsubstr_replace 函数返回奇怪的符号以及字符串
【发布时间】:2013-12-29 04:45:46
【问题描述】:

我有一个变量,里面有一些字符串,例如:

$var = "myText";

我想要做的是在最后一个单词之前“注入”一个单引号(')所以输出将是:

myTex't

我有这个代码:

$var = "myText";
$var = substr_replace($var, "'", strlen($var)-1, 0);
echo $var;

而且效果很好。唯一的问题是,当我尝试将它实现为另一种语言(在这种情况下为希伯来语)时,我得到了额外的字符。例如,对于那个输入:

עברית 我期待的结果是:עברי'ת,但结果却是:עברי�'�

有什么想法吗?

附注希伯来语是从右到左的语言

【问题讨论】:

    标签: php string substring


    【解决方案1】:

    您使用的是多字节字符串,而 substr_replace 与多字节不兼容。

    这是一个完全模仿 substr_replace() 行为的版本:(来自substr_replace PHP Manual 用户评论)

    <?php
    
    if (function_exists('mb_substr_replace') === false)
     {
         function mb_substr_replace($string, $replacement, $start, $length = null, $encoding = null)
         {
             if (extension_loaded('mbstring') === true)
             {
                 $string_length = (is_null($encoding) === true) ? mb_strlen($string) : mb_strlen($string, $encoding);
    
                 if ($start < 0)
                 {
                     $start = max(0, $string_length + $start);
                 }
    
                 else if ($start > $string_length)
                 {
                     $start = $string_length;
                 }
    
                 if ($length < 0)
                 {
                     $length = max(0, $string_length - $start + $length);
                 }
    
                 else if ((is_null($length) === true) || ($length > $string_length))
                 {
                     $length = $string_length;
                 }
    
                 if (($start + $length) > $string_length)
                 {
                     $length = $string_length - $start;
                 }
    
                 if (is_null($encoding) === true)
                 {
                     return mb_substr($string, 0, $start) . $replacement . mb_substr($string, $start + $length, $string_length - $start - $length);
                 }
    
                 return mb_substr($string, 0, $start, $encoding) . $replacement . mb_substr($string, $start + $length, $string_length - $start - $length, $encoding);
             }
    
             return (is_null($length) === true) ? substr_replace($string, $replacement, $start) : substr_replace($string, $replacement, $start, $length);
         }
     }
    
    ?>
    

    【讨论】:

    • 那么使用它的方法是什么?只需致电substr_replace?
    • 致电mb_substr_replace
    【解决方案2】:

    发生这种情况是因为您使用的是 unicode 多字节字符串。 substr_replace() 按字节工作。所以如果你只是替换最后一个字节,它可能会破坏最后一个字符(如果这是一个多字节字符)。

    使用可以使用preg_replace而不是substr_replace(),如果你通过u选项它是unicode安全的:

    preg_replace('~(.)$~u', '\'$1', $string);
    

    【讨论】:

    • 什么时候用?在我被奇怪的输出返回之后?
    • 用它代替 subtring_replace()
    • 不幸的是,它不起作用。与substr_replace 方法的结果相同
    猜你喜欢
    • 1970-01-01
    • 2014-02-28
    • 2016-10-11
    • 2014-08-11
    • 1970-01-01
    • 1970-01-01
    • 2019-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多