【问题标题】:Php truncate with ascii symbolsphp 用 ascii 符号截断
【发布时间】:2017-04-19 15:33:59
【问题描述】:

我的 Php 截断函数有问题...

我的代码是这样的:

// truncate long word
            $textArray = explode ( " ", $text );
            $DEBUG = 1;
            if ($DEBUG == 1) {
                print_r("// truncate long word");
                print_r($textArray);
                print_r("// END truncate long word");
                print_r("<br>");
            }

            foreach ( $textArray as $key => $word ) {
                if (mb_strlen ($word) > $wordsLenght) {
                    $truncatedWord = mb_substr ($word, 0, $wordsLenght);
                    $textArray [$key] = $truncatedWord . "[...]";
                }
            }

例如,假设输入字符串是“cia???☺☻♥♀♂☼•◘○♠♣xas?????!!!!----”(不带引号)这个我的结果是否打印为 print_r:

    // truncate long wordArray
    (
        [0] => cia???☺☻♥♀♂☼•◘○♠♣xas?????!!!!----
    )
    // END truncate long word

Result ($textArray)
    (
        [0] => cia???☺☻♥♀��[...]
    )

如您所见,字符串终止不正确,可能是由什么引起的?

【问题讨论】:

  • 请看这个刚刚拍摄的屏幕截图! i.imgur.com/GAZaNCN.png ..如您所见,结果与您发布的不一样..为什么? :(
  • 您的$wordsLenght 值是多少,mb_internal_encoding 返回的值是多少?您保存php文件时使用了哪种编码,在浏览器上阅读时使用的是哪种编码?
  • 现在我把 "mb_internal_encoding("UTF-8");"前截断操作(在第一个 foreach cicle 中)和提供的字符串完美返回!但是如果我在末尾使用法语/西班牙语字符(最后一个数组键)我看不到“[...]”...尝试使用这个字符串“sÀà, Ââ, Ææssdsasddssdsasasa”...我得到i.imgur.com/NUQCvH4.png
  • 你没有回答我之前的问题,直到你回答我才能帮助你更多

标签: php arrays truncate


【解决方案1】:

根据标题,在终端中使用 ASCI 转义序列时,此问题会变得最严重。

这是战斗的结局,使用php-mbstring

mb_strcut() 从字符串中提取子字符串,类似于 mb_substr(),但对字节而不是字符进行操作。如果切 位置恰好在多字节字符的两个字节之间, 从该字符的第一个字节开始执行剪切。 这也是 substr() 函数的不同之处,它会 只需剪切字节之间的字符串,从而导致格式错误 字节序列。

例如,以下函数将在给定长度处截断 ANSI 红星 * 的字符串。

它是双向的,输入字符串可以包含 ASCI 序列和 unicode,输出也可以包含一些,用于标记。

<?php

function strunkate($me, $at, $by = "*"){
  $l = mb_strlen($me);
  $t = mb_strcut($me,0,$at/2);
  $r = mb_strcut($me,$at/2, $l - $at);
  $me = str_replace($t,rtrim($t),str_replace($r, "\033[31;1m".$by."\e[0m", $me));
  return $me;
}

/* Examples */
echo strunkate("Screenshot at 2019-09-09 02-36-46.png",8);
echo "\n";
echo strunkate("Screenshot \033[1mat 2019-09-09\e[0m 02-36-46Super_long_string_with ansi_escape_sequences.png",8);
echo "\n";
echo strunkate("Screenshot \033[1mat 2019-09-09\e[0m 02-36-46Super_long_string_with ansi_escape_sequences.png",24);

/* Output an ASCI red star. No breaking  */
Scre[31;1m*[0m.png
Scre[31;1m*[0m.png
Screenshot [31;1m*[0mequences.png

在线运行:https://3v4l.org/2nJla

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-08
    • 1970-01-01
    相关资源
    最近更新 更多