richwol richwol - 8 months ago 47
PHP Question

PHP - strlen returning incorrect string length caused by quote

I have the following string coming from a database: Let's Get Functional

If I run this through strlen it returns 25 characters instead of the expected 20. A var dump shows that the string looks like the above (no html references etc).

If I remove the single quote strlen returns 19 characters.

Obviously the quote is returning 5 characters instead of 1 - why? How can I stop this?



As @deformhead already explained, it seems that your apostrophe has been converted to the HTML ' string. My guess would be that between getting the string out of the database and calling strlen() on it you call htmlentities() somewhere in-between.

You can also check how many characters you get from the database in your select query with CHAR_LENGTH() (MySQL).

Another issue you might consider is that strlen() does not work well for multibyte characters so if you'll be working with non-ASCII characters then you'd better use mb_strlen() with the correct encoding. This case however would not explain the difference of 5 characters in your result (strlen() counts the bytes and not characters in a string).

Hope that helps.