gpt4 book ai didi

javascript - 为什么 PHP strlen() 和 Javascript xxx.length 不相等?

转载 作者:行者123 更新时间:2023-11-30 11:25:21 25 4
gpt4 key购买 nike

我有以下文字:

Ankylosaurus was an armored dinosaur that lived roughly 67 million years ago, at the very end of the Cretaceous Period. This genus was among the last of the non-avian dinosaurs, living alongside Tyrannosaurus, Triceratops, and Edmontosaurus. Its name means 'fused lizard'; bones in its skull and other parts of its body were fused, increasing their strength. Ankylosaurus was up to 6.25 m (20.5 feet) long and 1.7 m (5.6 feet) tall, weighing about 4.8–8 tonnes (11,000–18,000 lb). It had a broad, robust body with a wide, low skull. The front parts of the jaws were covered in a beak, with rows of small, leaf-shaped teeth behind it, adapted for a herbivorous diet. It was covered in armor plates for protection against predators, with bony half-rings covering the neck, and had a large club on the end of its tail which may have been used as a weapon. Fossils from a few specimens of Ankylosaurus have been found in various geological formations in western North America, but a complete skeleton has

现在我运行下面的 PHP 和 JS 代码:

echo strlen(trim($text));

var text = "above text";
alert( text.length);

现在 PHP 显示 1004 而 JS 显示 1000 个字符,为什么?

最佳答案

您的两个版本不太可能打印相同的输出,因为它们执行不同的操作。

JavaScript's String.length property返回一个字符数(虽然基于早期和过时的字符定义):

console.log(`–`.length);
console.log(`💩`.length);

PHP's strlen() function返回一个字节数,您可能正在使用像 UTF-8 这样的多字节编码(或者您应该使用)。请比较:

var_dump(strlen('–'), mb_strlen('–'));
var_dump(strlen('💩'), mb_strlen('💩'));
int(3)
int(1)
int(4)
int(1)

您还仅在 JavaScript 版本中删除了前导和尾随空格,空格也是人。


构建可靠的字符计数跨语言函数:

  • PHP: mb_strlen()开箱即用,只要您将应用程序配置为告诉 PHP 正在使用的编码(或每次都手动指定编码)并为其提供正确编码的数据。在 2018 年,通常没有理由使用 UTF-8 之外的任何其他语言。

    var_dump(mb_strlen('–💩', 'UTF-8'));
  • JavaScript:String.length如果您认为不需要考虑表情符号,这似乎对您有用,但为了安全起见,您可以查看 JavaScript has a Unicode problem用于一些解决方法(即使出于纯粹的学习目的,这篇文章也很有趣)。

关于javascript - 为什么 PHP strlen() 和 Javascript xxx.length 不相等?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48261998/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com