Fallou
Fallou

Reputation: 23

Why doesn't mb_substr and mb_strlen work as expected in this case?

I'm trying to remove the first and last chars of a string. I'm experiencing weirdness.

Check it out:

$string = 'This is a test.';
$string = mb_substr($string, 1, mb_strlen($string) - 1);
var_dump($string);

Output:

string(14) "his is a test."

And then this:

$string = 'This is a test.';
$string = mb_substr($string, 1, mb_strlen($string) - 2);
var_dump($string);

Output:

string(13) "his is a test"

The length of the string minus 1 should be enough, but I have to go TWO minus. Why?

Upvotes: 2

Views: 98

Answers (1)

u_mulder
u_mulder

Reputation: 54796

Because your string This is a test. length is 15.

To get new string without last and first symbols - you need 13 symbols, which is exactly mb_strlen($string) - 2.

Also, third argument of mb_substr is not position of last considered symbol, it is length of the substring that you want to receive.

Upvotes: 2

Related Questions