简体   繁体   中英

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 that 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.

如果您具有非ASCII字符,请使用strlenmb_strlen

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

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

You can use mb_strlen to get the correct 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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