mb_substr
mb_substr(string $string, int $start, ?int $length = null, ?string $encoding = null): string
Multibyte-safe character-level substring: contrasted with byte-level substr to demonstrate PHP's dual-track string API — most languages have naturally character-level strings with no mb_ prefix.
C C23
#include <stdio.h>
#include <string.h>
/* byte offset where the n-th UTF-8 character starts (n counted from 0) */
static size_t utf8_offset(const char *s, int n) {
size_t off = 0;
int chars = 0;
while (s[off] != '\0') {
if ((s[off] & 0xC0) != 0x80) { /* continuation bytes are 10xxxxxx */
if (chars == n) return off;
chars++;
}
off++;
}
return off;
}
static size_t utf8_len(const char *s) {
size_t chars = 0;
for (size_t i = 0; s[i] != '\0'; i++) {
if ((s[i] & 0xC0) != 0x80) chars++;
}
return chars;
}
int main(void) {
const char *s = "你好世界";
size_t a = utf8_offset(s, 1), b = utf8_offset(s, 3);
printf("%.*s\n", (int)(b - a), s + a); /* chars 1-2 */
printf("%s\n", s + utf8_offset(s, 2)); /* last 2 chars */
printf("%zu %zu\n", utf8_len(s), strlen(s)); /* 4 chars vs 12 bytes */
return 0;
}
好世 世界 4 12
C++ C++26
#include <iostream>
#include <string>
// C++ strings are byte strings; locate the UTF-8 code point offset first
static size_t utf8_offset(const std::string& s, size_t n) {
size_t off = 0, chars = 0;
while (off < s.size()) {
if ((s[off] & 0xC0) != 0x80) { /* continuation bytes are 10xxxxxx */
if (chars == n) return off;
chars++;
}
off++;
}
return off;
}
static size_t utf8_len(const std::string& s) {
size_t chars = 0;
for (char ch : s) {
if ((ch & 0xC0) != 0x80) chars++;
}
return chars;
}
int main() {
std::string s = "你好世界";
std::cout << s.substr(utf8_offset(s, 1), utf8_offset(s, 3) - utf8_offset(s, 1)) << "\n"; // chars 1-2
std::cout << s.substr(utf8_offset(s, 2)) << "\n"; // last 2 chars
std::cout << utf8_len(s) << " " << s.size() << "\n"; // 4 chars vs 12 bytes
return 0;
}
好世 世界 4 12
C# v11.0.100
// C# strings are character-level (UTF-16, BMP-safe) - no mb_ prefix needed
var s = "你好世界";
Console.WriteLine(s.Substring(1, 2)); // chars 1-2
Console.WriteLine(s[^2..]); // last 2 chars via the range indexer
Console.WriteLine($"{s.Length} {System.Text.Encoding.UTF8.GetByteCount(s)}");
好世 世界 4 12
Go v1.27.4
package main
import (
"fmt"
"unicode/utf8"
)
func main() {
s := "你好世界"
r := []rune(s) // []rune is the character view of a UTF-8 string
fmt.Println(string(r[1:3])) // chars 1-2
fmt.Println(string(r[len(r)-2:])) // last 2 chars
fmt.Println(utf8.RuneCountInString(s), len(s)) // 4 chars vs 12 bytes
}
好世 世界 4 12
Java v27.0.1
public class Main {
public static void main(String[] args) {
String s = "你好世界";
System.out.println(s.substring(1, 3)); // chars 1-2 (UTF-16 units, BMP-safe)
System.out.println(s.substring(s.length() - 2)); // last 2 chars
System.out.println(s.length() + " " + s.getBytes(java.nio.charset.StandardCharsets.UTF_8).length);
}
}
好世 世界 4 12
JavaScript v26.13.1
// JS strings are UTF-16; BMP CJK is one code unit - no dual-track API needed
const s = "你好世界";
console.log(s.substring(1, 3)); // chars 1-2
console.log(s.slice(-2)); // last 2 chars
console.log(s.length, Buffer.byteLength(s)); // 4 UTF-16 units vs 12 bytes
好世 世界 4 12
PHP v8.6.0
// mb_substr counts CHARACTERS; plain substr counts BYTES
$s = "你好世界"; // 4 characters, 12 UTF-8 bytes
echo mb_substr($s, 1, 2), "\n"; // characters 1-2 (0-based)
echo mb_substr($s, -2), "\n"; // negative start counts from the end
echo bin2hex(substr($s, 1, 2)), "\n"; // byte-level substr lands mid-character: bda0
好世 世界 bda0
Python v3.15.2
# Python strings are character sequences natively - no dual-track API
s = "你好世界"
print(s[1:3]) # chars 1-2 (0-based)
print(s[-2:]) # last 2 chars
print(len(s), len(s.encode("utf-8"))) # 4 chars vs 12 bytes
好世 世界 4 12
Rust v1.99.1
fn main() {
let s = "你好世界";
let v: Vec<char> = s.chars().collect(); // chars() is the character view
let sub: String = v[1..3].iter().collect();
println!("{}", sub); // chars 1-2
let tail: String = v[v.len() - 2..].iter().collect();
println!("{}", tail); // last 2 chars
println!("{} {}", s.chars().count(), s.len()); // 4 chars vs 12 bytes
}
好世 世界 4 12
TypeScript v26.13.1
// Same UTF-16 semantics as JS; types add nothing here - which is the point
const s: string = "你好世界";
console.log(s.substring(1, 3)); // chars 1-2
console.log(s.slice(-2)); // last 2 chars
console.log(s.length, Buffer.byteLength(s)); // 4 UTF-16 units vs 12 bytes
好世 世界 4 12
Language differences
C: no multibyte substring function — the idiom is a hand-written scan: continuation bytes look like 10xxxxxx, so locate the byte offset of the n-th character and slice there (the C implementation of mb_substr is essentially the same idea); the example contrasts character count with byte count.
C++: std::string is also a byte string — scan UTF-8 code points to locate, then substr, same as C.
C#: Substring(start, length) and the range indexer s[^2..] are character-level (UTF-16; BMP CJK is 1 code unit); byte counts need explicit Encoding.UTF8.GetByteCount.
Go: a string is byte-indexed; []rune(s) is the character view — convert to a rune slice first, and express negative starts explicitly as len(r)-2.
Java: String.substring counts UTF-16 code units (safe for BMP CJK; supplementary characters take 2 units — the same family as the "JS pitfall").
JavaScript: substring/slice count UTF-16 code units — BMP CJK is naturally 1 unit, so no dual-track API like PHP's is needed; Buffer.byteLength shows bytes.
PHP: the dual-track string API lineage — byte-level substr slices by bytes (the example cuts out the invalid UTF-8 fragment bda0), while character level requires the mb_ prefix: mb_substr($s, 1, 2) counts characters. Negative start counts from the end; omitting encoding uses the internal encoding, and an invalid encoding throws ValueError since 8.0; since 8.3.2 character indices on invalid strings align with the other mbstring functions.
Python: the native string type is character-level — s[1:3] is a character substring with no byte/char dual-track trouble; bytes are a separate type, bytes, reached explicitly via s.encode().
Rust: &str is always UTF-8; s[0..3] indexes bytes and panics on a non-boundary, so character-level slicing goes through chars().collect::<Vec<char>>() (or unicode-segmentation for grapheme clusters).
TypeScript: same runtime as JS (UTF-16 code units); the string type has no byte/character distinction — the dual-track problem does not exist in TS.