Get the rest of the string to the end using mb_substr () and still set the encoding

With substr() you can omit the third parameter to get the rest of the string:

 substr('abcdefg', 2) // returns "cdefg" 

You cannot do the same with mb_substr() :

 mb_substr('abcdefg', 2, null, 'UTF-8'); // returns empty string 

I found only weird and ugly solutions.

  • Setting a very large number as a length:

    $a = mb_substr('abcdefg', 2, 9999999999, 'UTF-8');

  • Calculation of the number:

    $a = mb_substr('abcdefg', 2, mb_strlen('abcdefg', 'UTF-8') - 2, 'UTF-8');

  • Omitting the charset parameter with mb_internal_encoding() :

    $temp = mb_internal_encoding(); // prevent action at a distance
    mb_internal_encoding('UTF-8');
    $a = mb_substr('abcdefg', 2);
    mb_internal_encoding($temp);

Is there a real solution?

+6
source share
2 answers

The change log shows this as a bug fix in version 5.4.8 (October 18, 2012).

http://us.php.net/ChangeLog-5.php

Allow null as the default for mb_substr () and mb_strcut (). Patch of Alexander Moskalev via GitHub PR # 133.

There is also a link to the stretch request stream: https://github.com/php/php-src/pull/133

+2
source

This is the difference between PHP 5.3 (and probably also in earlier versions) and PHP 5.4.

Actually, you can see the problem in the PHP source code if you're interested.

This is the ext/mbstring/mbstring.c file, which has the following difference in the PHP_FUNCTION(mb_substr) function.

In PHP 5.3, they check this condition:

 if (argc < 3) { len = str_len; } 

While in PHP 5.4 they use:

 if (argc < 3 || Z_TYPE_PP(z_len) == IS_NULL) { len = str_len; } 

These definitions can be found in the implementation of the mb_string function, which is launched by PHP_FUNCTION(mb_substr) in the specified file. Source code can be downloaded from the php.net download page .

+2
source

All Articles