I want to count how many characters a certain string has in PHP, but I cant get it to work.
I did a var_dump and this is what I got:
string(23) "Children’s Center"
It seems like '
gets translated to ’s
This makes it impossible to get the actual character count. I tried using html_entity_decode
but it did not help.
Anyone?
EDIT: My function looks like this now:
function make_shorter($string, $maxlength)
开发者_运维技巧{
$string = stripslashes($string);
$string = html_entity_decode($string);
if ( mb_strlen(utf8_decode($string)) > $maxlength)
return substr($string,0,$maxlength).'...';
else
return $string;
}
I can't change how the data gets in to the system. I can only modify it's output.
(It's a wordpress site)
It seems like
'
gets translated to’
s
That's the HTML character reference for the single right smart-quote, ’
, which some people also use to represent an apostrophe (especially those typing in MS Word). At some prior point in your processing, something has applied htmlentities()
to your data.
HTML-escaping should only be carried out at the output stage, when inserting text into an HTML page. So look back and see if you've got a function doing something stupid like calling htmlentities()
over every entry in the $_POST
/$_GET
/$_REQUEST
array. This is a common but completely bogus way to try to prevent XSS attacks. If you see it, you are at some point going to need to take it out and go through your templates adding proper HTML-escaping around every time you drop a variable into HTML.
Either way, use htmlspecialchars()
instead of htmlentities()
and it'll leave the non-ASCII characters like ’
alone.
html_entity_decode()
definitely should undo the above encoding, leaving you with a raw string. ’
might still count as either one or two bytes, though, depending on what encoding you decode into. If you want to count characters properly and you have UTF-8 strings, you will need mb_strlen()
.
You're using a right single quotation mark, instead of the ' character. Well... stop that!
$string = "Children's Center";
echo strlen($string); // 17
Google this to see the difference: ’ '
echo strlen($myString);
or
echo strlen(utf8_decode($myString));
?
Try strlen(), It will solve
精彩评论