简体   繁体   English

如何使用PHP准确计算带有特殊字符的字符串中的字符数?

[英]How can I accurately calculate the number of characters in a string with special characters using PHP?

I'm using strlen to calculate the length of a string and if it exceeds x characters, substr it with a ellipses. 我正在使用strlen来计算字符串的长度,如果它超过x个字符,则使用省略号对其进行substr The problem is, if there are special characters, the strlen function spits out an inaccurate number, causing ellipses to be added to strings that haven't exceeded x characters. 问题是,如果有特殊字符, strlen函数会吐出一个不准确的数字,导致省略号被添加到没有超过x个字符的字符串中。 What is a good method of calculating the length of a string in a way that works even with special characters involved, preferably counting a special character as a regular character so something like "W^a" counts as three characters. 以某种方式计算字符串长度的好方法是什么,即使涉及特殊字符也是如此,最好将特殊字符作为常规字符计数,这样“W ^ a”就像三个字符一样。

如果在special characters你的意思是öüóűőúéáí,你可以尝试使用mb_strlen方法http://www.php.net/manual/en/function.mb-strlen.php并将'utf-8'作为第二个参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM