Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why my php substr() shows obscure characters when cutting a text?

Tags:

php

I'm using the substr() function to limit the characters in strings. but sometimes, the output text contains some obscure characters and Question marks etc...

the text which is "substred" is already UTF8 encoded, and NOT in html entities to make like this problem.

Thanks

like image 849
CodeOverload Avatar asked Jan 23 '10 19:01

CodeOverload


People also ask

What is substr () in PHP and how it is used?

substr in PHP is a built-in function used to extract a part of the given string. The function returns the substring specified by the start and length parameter. It is supported by PHP 4 and above. Let us see how we can use substr() to cut a portion of the string.

What can I use instead of substring?

You can replace a substring using replace() method in Java. The String class provides the overloaded version of the replace() method, but you need to use the replace(CharSequence target, CharSequence replacement).

How do you split the first 5 characters of a string?

You can use the substr function like this: echo substr($myStr, 0, 5); The second argument to substr is from what position what you want to start and third arguments is for how many characters you want to return.

How can I get the first 3 characters of a string in PHP?

To get the first n characters from a string, we can use the built-in substr() function in PHP. Here is an example, that gets the first 3 characters from a following string. <? php echo substr("Ok-Google", 0, 3); ?>


2 Answers

Because you are cutting your characters into half.

Use mb_substr for multibyte character encodings like UTF-8. substr just counts bytes while mb_substr counts characters.

like image 148
Gumbo Avatar answered Dec 29 '22 16:12

Gumbo


The reason is that you use UTF-8, it's multibyte encoding,and substr() works with singlebyte only! htmlentities() doesn't matter.

You SHOULD use mb_substr() http://php.net/manual/en/function.mb-substr.php and other multibyte functions

like image 21
Dan Avatar answered Dec 29 '22 17:12

Dan