Skip to content
← Back to Snippets
Code

Get String Length

Returns byte length and, when available, UTF-8 character length for a string.

Purpose

Returns byte length and, when available, UTF-8 character length for a string.

Snippet details

ContextStringLevelProductionCopy-and-paste statusMarked safe after review.

Categories

  • Forms and Validation

Code

<?php

/*
 * Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
 * Free for personal and internal use. Paid project use requires visible credit
 * to Jeffery L. Paris. Corporate use requires a paid license fee unless a
 * separate written license states otherwise.
 */

/**
 * Get String Length.
 *
 * Purpose:
 * Returns the byte length and optional UTF-8 character length of a string.
 *
 * @param string $text Text to measure.
 * @return array Length details.
 */
function ogSnippetGetStringLength(string $text): array {
	$byte_length = strlen($text);
	$character_length = $byte_length;
	$length_source = 'strlen';

	if (function_exists('mb_strlen') === true) {
		$character_length = mb_strlen($text, 'UTF-8');
		$length_source = 'mb_strlen';
	}

	return array(
		'text' => $text,
		'byte_length' => $byte_length,
		'character_length' => $character_length,
		'length_source' => $length_source
	);
}

$length_report = ogSnippetGetStringLength('Rocinante');

echo 'String length: '.$length_report['character_length'];