kisabelle
kisabelle

Reputation: 591

mb_substr() returns a blank string UNLESS last two parameters are omitted

I am getting really weird results from mb_substr() that go against what the documentation describes as the expected behaviour: when I pass in the last two parameters, mb_substr() returns a blank string. If I omit the last two parameters completely, it returns the expected result. Is there something I am missing or something wrong with my syntax? EDIT: I am wondering if this could be happening due to a server setting, as this wasn't happening when I had my code on a local server using MAMP.

Documentation:

mb_substr ( string $str, int $start, int $length, string $encoding ) should return the portion of str specified by the start and length parameters.

length Maximum number of characters to use from str. If omitted or NULL is passed, extract all characters to the end of the string.

View on php.net


My code:

$mb2 = mb_substr('Hello I am a string', 6, NULL, 'UTF-8'); echo 'mb2: ' . $mb2;

Expected behavior:

mb2: I am a string

Actual results:

mb2:


My modified code:

$mb2 = mb_substr('Hello I am a string', 6); echo 'mb2: ' . $mb2;

Actual results:

mb2: I am a string

Upvotes: 0

Views: 1088

Answers (2)

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111899

Everything depends on PHP version you use. I've just tested it on my localhost changing PHP versions.

For the following code:

<?php

$mb2 = mb_substr('Hello I am a string', 6, NULL, 'UTF-8');
echo 'mb2: ' . $mb2;

PHP 5.6 outputs: mb2: I am a string

PHP 5.5.11 outputs: mb2: I am a string

PHP 5.4.31 outputs: mb2: I am a string

PHP 5.3.29 outputs: mb2:

So it seems there was a bug in previous PHP versions or PHP documentation has changed and earlier there was another documentation for PHP.

And to create safe code (working also in PHP 5.3) you could use:

<?php
mb_internal_encoding('UTF-8');
$mb2 = mb_substr('Hello I am a string', 6);
echo 'mb2: ' . $mb2;

This will give the same result in all PHP 5.3+ versions

EDIT

Looking at PHP Changelog you can read:

Allow passing null as a default value to mb_substr() and mb_strcut(). Patch by Alexander Moskaliov via GitHub PR #133.

as of 5.4.8 so from this version it should work fine

Upvotes: 2

Ali Gajani
Ali Gajani

Reputation: 15089

This is the correct way to use it. As it says in the comments, passing as NULL makes it interpret it as 0.

$mb2 = mb_substr('Hello I am a string',6,mb_strlen('Hello I am a string'),'utf-8');

http://ideone.com/wYPYWM

Upvotes: 2

Related Questions