Skip to content
← Back to Snippets
Code

Get a Substring

Extracts a substring from a string with explicit start and length bounds.

Purpose

Extracts a substring from a string with explicit start and length bounds.

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 a Substring.
 *
 * Purpose:
 * Extracts part of a string after normalizing the requested start and length.
 *
 * @param string $text Source text.
 * @param int $start Zero-based start position.
 * @param int $length Number of characters to read.
 * @return array Substring result.
 */
function ogSnippetGetASubstring(string $text, int $start, int $length): array {
	$text_length = strlen($text);

	if ($start < 0) {
		$start = 0;
	}

	if ($length < 0) {
		$length = 0;
	}

	if ($start > $text_length) {
		$start = $text_length;
	}

	$substring = substr($text, $start, $length);

	if ($substring === false) {
		$substring = '';
	}

	return array(
		'original' => $text,
		'start' => $start,
		'length' => $length,
		'substring' => $substring
	);
}

$sample = ogSnippetGetASubstring('Serenity cargo manifest', 0, 8);

echo 'Substring: '.$sample['substring'];