Skip to content
← Back to Snippets
Code

Check if String Contains a Substring

Checks whether a string contains a requested substring and returns the first match position.

Purpose

Checks whether a string contains a requested substring and returns the first match position.

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.
 */

/**
 * Check if String Contains a Substring.
 *
 * Purpose:
 * Finds whether a string contains another string using strpos().
 *
 * @param string $text Text to search.
 * @param string $needle Text to find.
 * @return array Search result.
 */
function ogSnippetCheckIfStringContainsSubstring(string $text, string $needle): array {
	if ($needle === '') {
		return array(
			'contains' => false,
			'position' => false,
			'message' => 'Needle is empty.'
		);
	}

	$position = strpos($text, $needle);
	$contains = false;
	$message = 'Substring was not found.';

	if ($position !== false) {
		$contains = true;
		$message = 'Substring was found.';
	}

	return array(
		'contains' => $contains,
		'position' => $position,
		'message' => $message
	);
}

$contains_report = ogSnippetCheckIfStringContainsSubstring('Aliens motion tracker active', 'tracker');

echo 'Contains result: '.$contains_report['message'];