开发者

How to count all characters including spaces and regex in php?

how can I count all characters? I am selecting a field from mysql (which is a plain text) and I would like to count all letters in that text th开发者_JAVA百科at is extracted (including spaces and all special characters).

I am comparing the value with a number, for example:

If text has more than 1000 characters then $var++ so I know how many fields have more than 1000 characters.

strlen does not seems to be counting right.


Use strlen or mb_strlen if you have non-ASCII characters.


This probably happens because of encoding issues. This has nothing to do with regexs.

You can use mb_strlen to get the correct length.


You need mb_strlen() for Unicode characters: http://php.net/manual/en/function.mb-strlen.php

On the other hand if you're just counting how many entries in the database have more than 1000 characters, you can save some computing power with the MySQL function CHAR_LENGTH() to count the total in the database: http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_char-length


You could let mysql do the counting as it knows the charset, has a counting function and can even give you the number of fields in a table that have more then 1000 characters directly:

SELECT count(*) as var FROM table WHERE CHAR_LENGTH(field) > 1000;

This will return your var as mysql result. This will spare you to return the whole table data just to obtain this number.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜