grapheme_substr

grapheme_substr(string $string, int $offset, ?int $length = null, string $locale = ""): string|false

Substring by grapheme cluster: taking grapheme [1,2) of "a👨‍👩‍👧b" yields the whole family emoji, not half a code point — mb_substr with the same arguments returns only the MAN; negative offsets count from the tail, and out-of-range yields an empty string.

C C23

C23
#include <stdio.h>
#include <string.h>

/* Decode one UTF-8 code point; returns its byte length (0 at end of input) */
static size_t decode_utf8(const unsigned char *s, size_t n, unsigned *cp) {
    if (n == 0) return 0;
    if (s[0] < 0x80) { *cp = s[0]; return 1; }
    if ((s[0] & 0xE0) == 0xC0 && n >= 2) { *cp = ((s[0] & 0x1F) << 6) | (s[1] & 0x3F); return 2; }
    if ((s[0] & 0xF0) == 0xE0 && n >= 3) { *cp = ((s[0] & 0x0F) << 12) | ((s[1] & 0x3F) << 6) | (s[2] & 0x3F); return 3; }
    if ((s[0] & 0xF8) == 0xF0 && n >= 4) { *cp = ((s[0] & 0x07) << 18) | ((s[1] & 0x3F) << 12) | ((s[2] & 0x3F) << 6) | (s[3] & 0x3F); return 4; }
    *cp = 0xFFFD; return 1;
}

/* Simplified Grapheme_Cluster_Break spans: CR / LF / Extend / ZWJ only —
   fills spans with cluster [start_byte, end_byte) pairs, returns cluster count */
static int cluster_spans(const char *str, size_t spans[][2]) {
    const unsigned char *s = (const unsigned char *)str;
    size_t n = strlen(str), i = 0;
    int count = 0, have_prev = 0;
    unsigned prev = 0, cp;
    while (i < n) {
        size_t start = i;
        i += decode_utf8(s + i, n - i, &cp);
        int extend = (cp >= 0x0300 && cp <= 0x036F);
        int join = (cp == 0x200D) || (cp == 0x0A && prev == 0x0D) || (have_prev && prev == 0x200D);
        if (count > 0 && (extend || join)) { prev = cp; have_prev = 1; continue; } /* stays inside the previous cluster */
        if (count > 0) spans[count - 1][1] = start;
        spans[count][0] = start;
        spans[count][1] = n;
        count++;
        prev = cp;
        have_prev = 1;
    }
    return count;
}

/* grapheme_substr($s, $start, $length) on cluster indexes */
static void slice_print(const char *s, size_t spans[][2], int n, int start, int length) {
    if (start < 0) start += n;
    if (start < 0) start = 0;
    int end = n;
    if (length >= 0 && start + length < end) end = start + length;
    if (length < 0) end = n + length;
    if (start >= n || end <= start) { putchar('\n'); return; }
    fwrite(s + spans[start][0], 1, spans[end - 1][1] - spans[start][0], stdout);
    putchar('\n');
}

int main(void) {
    const char *s = "a\xF0\x9F\x91\xA8\xE2\x80\x8D\xF0\x9F\x91\xA9\xE2\x80\x8D\xF0\x9F\x91\xA7" "b"; /* clusters: a | family | b */
    size_t spans[8][2];
    int n = cluster_spans(s, spans);
    slice_print(s, spans, n, 1, 1);  /* the WHOLE family */
    slice_print(s, spans, n, 1, 99); /* family + b (positive length clamps like a null length) */
    slice_print(s, spans, n, -1, 1); /* "b": negative offset counts clusters */
    return 0;
}
Output
👨‍👩‍👧
👨‍👩‍👧b
b

C++ C++26

C++26
#include <cstdio>
#include <string>
#include <utility>
#include <vector>

// Decode one UTF-8 code point; returns its byte length (0 at end of input)
static size_t decodeUtf8(const unsigned char *s, size_t n, unsigned &cp) {
    if (n == 0) return 0;
    if (s[0] < 0x80) { cp = s[0]; return 1; }
    if ((s[0] & 0xE0) == 0xC0 && n >= 2) { cp = ((s[0] & 0x1F) << 6) | (s[1] & 0x3F); return 2; }
    if ((s[0] & 0xF0) == 0xE0 && n >= 3) { cp = ((s[0] & 0x0F) << 12) | ((s[1] & 0x3F) << 6) | (s[2] & 0x3F); return 3; }
    if ((s[0] & 0xF8) == 0xF0 && n >= 4) { cp = ((s[0] & 0x07) << 18) | ((s[1] & 0x3F) << 12) | ((s[2] & 0x3F) << 6) | (s[3] & 0x3F); return 4; }
    cp = 0xFFFD; return 1;
}

// Simplified Grapheme_Cluster_Break spans: CR / LF / Extend / ZWJ only
static std::vector<std::pair<size_t, size_t>> clusterSpans(const std::string &str) {
    const unsigned char *s = reinterpret_cast<const unsigned char *>(str.data());
    size_t n = str.size(), i = 0;
    std::vector<std::pair<size_t, size_t>> spans;
    int havePrev = 0;
    unsigned prev = 0, cp;
    while (i < n) {
        size_t start = i;
        i += decodeUtf8(s + i, n - i, cp);
        bool extend = cp >= 0x0300 && cp <= 0x036F;
        bool join = cp == 0x200D || (cp == 0x0A && prev == 0x0D) || (havePrev && prev == 0x200D);
        if (!spans.empty() && (extend || join)) { prev = cp; havePrev = 1; continue; } // stays inside the previous cluster
        if (!spans.empty()) spans.back().second = start;
        spans.emplace_back(start, n);
        prev = cp;
        havePrev = 1;
    }
    return spans;
}

// grapheme_substr($s, $start, $length) on cluster indexes
static std::string gsubstr(const std::string &s, int start, int length) {
    auto spans = clusterSpans(s);
    int n = (int)spans.size();
    if (start < 0) start += n;
    if (start < 0) start = 0;
    int end = n;
    if (length >= 0 && start + length < end) end = start + length;
    if (length < 0) end = n + length;
    if (start >= n || end <= start) return "";
    return s.substr(spans[start].first, spans[end - 1].second - spans[start].first);
}

int main() {
    const std::string s = "a\xF0\x9F\x91\xA8\xE2\x80\x8D\xF0\x9F\x91\xA9\xE2\x80\x8D\xF0\x9F\x91\xA7" "b"; // clusters: a | family | b
    std::printf("%s\n", gsubstr(s, 1, 1).c_str());  // the WHOLE family
    std::printf("%s\n", gsubstr(s, 1, 99).c_str()); // family + b (positive length clamps like a null length)
    std::printf("%s\n", gsubstr(s, -1, 1).c_str()); // "b": negative offset counts clusters
    return 0;
}
Output
👨‍👩‍👧
👨‍👩‍👧b
b

C# v11.0.100

v11.0.100
using System.Globalization;

var s = "a👨‍👩‍👧b"; // text elements: a | family | b
var si = new StringInfo(s);
Console.WriteLine(si.SubstringByTextElements(1, 1)); // the WHOLE family
Console.WriteLine(si.SubstringByTextElements(1));     // family + b
Console.WriteLine(si.SubstringByTextElements(si.LengthInTextElements - 1)); // "b"
Output
👨‍👩‍👧
👨‍👩‍👧b
b

Go v1.27.4

v1.27.4
package main

import "fmt"

// no grapheme segmentation in the stdlib — hand-roll the simplified
// Grapheme_Cluster_Break rule (CR/LF/Extend/ZWJ), then slice by cluster index
func clusterSpans(s string) [][2]int {
	var spans [][2]int
	var prev rune
	for i, r := range s { // i = byte offset of the decoded rune
		extends := r >= 0x0300 && r <= 0x036F
		joins := r == 0x200D || (r == 0x0A && prev == 0x0D) || prev == 0x200D
		if len(spans) > 0 && (extends || joins) {
			// stay in the current cluster
		} else {
			if len(spans) > 0 {
				spans[len(spans)-1][1] = i
			}
			spans = append(spans, [2]int{i, i})
		}
		prev = r
	}
	if len(spans) > 0 {
		spans[len(spans)-1][1] = len(s)
	}
	return spans
}

func main() {
	s := "a👨‍👩‍👧b" // clusters: a | family | b
	spans := clusterSpans(s)
	slice := func(start, length int) string {
		n := len(spans)
		if start < 0 {
			start += n
		}
		end := n
		if length >= 0 && start+length < end {
			end = start + length
		}
		if length < 0 {
			end = n + length
		}
		if start < 0 || start >= n || end <= start {
			return ""
		}
		return s[spans[start][0]:spans[end-1][1]]
	}
	fmt.Println(slice(1, 1))  // the WHOLE family
	fmt.Println(slice(1, 99)) // family + b (positive length clamps like a null length)
	fmt.Println(slice(-1, 1)) // "b": negative offset counts clusters
}
Output
👨‍👩‍👧
👨‍👩‍👧b
b

Java v27.0.1

v27.0.1
import java.text.BreakIterator;
import java.util.ArrayList;
import java.util.List;

public class Main {
    // BreakIterator.getCharacterInstance gives the cut points ≈ grapheme clusters
    static String gsubstr(String s, int start, Integer length) {
        BreakIterator it = BreakIterator.getCharacterInstance();
        it.setText(s);
        List<Integer> cuts = new ArrayList<>();
        for (int p = it.first(); p != BreakIterator.DONE; p = it.next()) {
            cuts.add(p);
        }
        int n = cuts.size() - 1; // cluster count
        if (start < 0) start = n + start;
        if (start < 0) start = 0;
        if (start >= n) return "";
        int end = (length == null) ? n : (length < 0 ? n + length : Math.min(start + length, n));
        return s.substring(cuts.get(start), cuts.get(end));
    }

    public static void main(String[] args) {
        String s = "a👨‍👩‍👧b"; // clusters: a | family | b
        System.out.println(gsubstr(s, 1, 1));   // the WHOLE family
        System.out.println(gsubstr(s, 1, null)); // family + b (null length = to the end)
        System.out.println(gsubstr(s, -1, 1));  // "b": negative offset counts clusters
    }
}
Output
👨‍👩‍👧
👨‍👩‍👧b
b

JavaScript v26.13.1

v26.13.1
// Intl.Segmenter (ES2022) gives grapheme cut points — slice without tearing emoji
const seg = new Intl.Segmenter("en", { granularity: "grapheme" });
const cuts = (s) => [0, ...Array.from(seg.segment(s), (x) => x.index + x.segment.length)];
const gsubstr = (s, start, length) => {
  const c = cuts(s), n = c.length - 1;
  if (start < 0) start += n;
  if (start < 0) start = 0;
  if (start >= n) return "";
  const end = length === undefined ? n : length < 0 ? n + length : Math.min(start + length, n);
  return s.slice(c[start], c[end]);
};
const s = "a👨‍👩‍👧b"; // segments: a | family | b
console.log(gsubstr(s, 1, 1));  // the WHOLE family
console.log(gsubstr(s, 1));     // family + b (no length = to the end)
console.log(gsubstr(s, -1, 1)); // "b": negative offset counts segments
Output
👨‍👩‍👧
👨‍👩‍👧b
b

PHP v8.6.0

v8.6.0
// grapheme_substr cuts BETWEEN grapheme clusters — the family emoji stays whole
$s = "a👨‍👩‍👧b"; // graphemes: a | family | b
echo grapheme_substr($s, 1, 1), "\n"; // the WHOLE family (one grapheme)
echo grapheme_substr($s, 1), "\n";    // family + b (null length = to the end)
echo grapheme_substr($s, -1), "\n";   // "b": negative offset counts graphemes
echo grapheme_substr($s, 5, 2) === "" ? "out-of-range -> empty string\n" : "?\n";
// char-level contrast: mb_substr would saw the family in half
echo mb_substr($s, 1, 1, "UTF-8"), "\n"; // just the MAN (first code point)
Output
👨‍👩‍👧
👨‍👩‍👧b
b
out-of-range -> empty string
👨

Python v3.15.2

v3.15.2
# No grapheme segmentation in the stdlib — hand-roll the simplified
# Grapheme_Cluster_Break rule (CR/LF/Extend/ZWJ), then slice by cluster index
def cluster_spans(s):
    spans, prev = [], None
    for i, ch in enumerate(s):
        cp = ord(ch)
        extends = 0x0300 <= cp <= 0x036F            # Extend: keep inside the cluster
        joins = cp == 0x200D or (cp == 0x0A and prev == 0x0D) or prev == 0x200D
        if spans and (extends or joins):
            pass                                    # stay in the current cluster
        else:
            if spans:
                spans[-1] = (spans[-1][0], i)
            spans.append((i, i))
        prev = cp
    if spans:
        spans[-1] = (spans[-1][0], len(s))
    return spans

s = "a👨‍👩‍👧b"  # clusters: a | family | b
spans = cluster_spans(s)

def gsubstr(start, length=None):
    n = len(spans)
    if start < 0:
        start += n
    end = n if length is None else (n + length if length < 0 else min(start + length, n))
    if start < 0 or start >= n or end <= start:
        return ""
    return s[spans[start][0]:spans[end - 1][1]]

print(gsubstr(1, 1))  # the WHOLE family
print(gsubstr(1))     # family + b (length None = to the end)
print(gsubstr(-1))    # "b": negative offset counts clusters
Output
👨‍👩‍👧
👨‍👩‍👧b
b

Rust v1.99.1

v1.99.1
use unicode_segmentation::UnicodeSegmentation;

fn main() {
    // graphemes(true) yields clusters — slice by cluster index, never by byte
    let s = "a👨‍👩‍👧b"; // clusters: a | family | b
    let g: Vec<&str> = s.graphemes(true).collect();
    println!("{}", g[1]);           // the WHOLE family
    println!("{}", &g[1..].concat()); // family + b
    println!("{}", g[2]);           // "b"
}
Output
👨‍👩‍👧
👨‍👩‍👧b
b

TypeScript v26.13.1

v26.13.1
// Intl.Segmenter (ES2022) gives grapheme cut points — slice without tearing emoji
const seg = new Intl.Segmenter("en", { granularity: "grapheme" });
const cuts = (s: string): number[] => [0, ...Array.from(seg.segment(s), (x) => x.index + x.segment.length)];
const gsubstr = (s: string, start: number, length?: number): string => {
  const c = cuts(s), n = c.length - 1;
  if (start < 0) start += n;
  if (start < 0) start = 0;
  if (start >= n) return "";
  const end = length === undefined ? n : length < 0 ? n + length : Math.min(start + length, n);
  return s.slice(c[start], c[end]);
};
const s: string = "a👨‍👩‍👧b"; // segments: a | family | b
console.log(gsubstr(s, 1, 1));  // the WHOLE family
console.log(gsubstr(s, 1));     // family + b (no length = to the end)
console.log(gsubstr(s, -1, 1)); // "b": negative offset counts segments
Output
👨‍👩‍👧
👨‍👩‍👧b
b

Language differences

PHP: grapheme_substr cuts between grapheme-cluster boundaries — the example takes grapheme [1,2) and gets the whole family emoji, while mb_substr with the same (character-level) arguments returns only the MAN (last line). A negative offset counts from the tail; since PHP 8.0 out-of-range offsets consistently clamp to an empty string (some cases used to return false — see the manual Changelog); the 4th parameter $locale was added in PHP 8.5. Requires the intl extension.

C: no grapheme segmentation in the stdlib — the example reuses the simplified Grapheme_Cluster_Break (CR/LF/Extend/ZWJ) to compute per-cluster byte spans, then slices by index; slice_print mirrors PHP semantics for negative offsets and out-of-range.

C++: same idea as C (std::string + vector-of-spans version); in production use ICU BreakIterator for the cut points, then substr.

C#: StringInfo.SubstringByTextElements(start, length) is the native counterpart — slices by text-element index (the family emoji comes out whole); there is no negative-offset overload, so convert via LengthInTextElements for tail access.

Go: no grapheme segmentation in the stdlib — the example hand-computes cluster spans, then slices by byte offsets (Go slices are byte ranges and must land on cluster boundaries); rivo/uniseg in production.

Java: BreakIterator yields a List of cut points; gsubstr slices by cluster index; a null length means "to the end" (matching PHP's null length).

JavaScript: Intl.Segmenter provides each segment's index; build the cut-point array and slice; omitting length means "to the end".

Python: no grapheme segmentation in the stdlib — the example hand-computes cluster spans, then slices by index; use the third-party regex module's \X in production.

Rust: unicode-segmentation's graphemes(true) collected into a Vec gives the simplest implementation — index directly; never slice by bytes.

TypeScript: same as JavaScript (Intl.Segmenter + cut-point slicing).

Determinism: the fixed string "a👨‍👩‍👧b" with fixed start/length indexes; the family emoji is a single cluster in every mainstream UAX #29 implementation (ICU BreakIterator, Intl.Segmenter, StringInfo, unicode-segmentation) and in the hand-written simplified rule, so slice results are byte-identical.