PHP substr回应错误的字符

I have a string:

‘I’m Part of a big MNC’: Tips on how you can rise to the top position.

I want the substring: ‘I’m Part

The string is stored in a variable called $title

My code:

<?php echo substr( $title, 0, 9 ); ?>

It returns ‘I’m on writephponline

and on webpage, it returns ‘I&

Any reason why this happens?

The problem will be with the quotes you are using in your original string.

If you use regular single quotes ', the correct output will be presented:

$title = "'I'm Part of a big MNC': Tips on how you can rise to the top position.";
echo substr( $title, 0, 9 );

Result:

'I'm Part

The issue here comes from the fact that substr() doesn't count characters but bytes.

Your input string is multi-byte; one character is represented on one or more bytes. The exact amount depends on the encoding of the string. Most probably it is UTF-8 but only you can tell it for sure.

Anyway, the solution to your problem is the mb_substr() function which is part of the PHP mb extension.

the problem is that your data isn't ASCII. you have to use multibyte-functions and tell PHP to use the correct encoding, probably UTF-8, internally.

this example worked as expected in writephponline:

<?php
mb_internal_encoding("UTF-8");
$string = "‘I’m Part of a big MNC’";
var_dump(mb_substr($string, 0, 9));
//output:  string(13) "‘I’m Part"