Reputation: 3798
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?
Upvotes: 2
Views: 65
Reputation: 3579
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"
Upvotes: 1
Reputation: 72425
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.
Upvotes: 2
Reputation: 3276
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
Upvotes: 1