SyntaxStudy
Sign Up
PHP Searching & Trimming Strings
PHP Beginner 6 min read

Searching & Trimming Strings

Finding substrings and removing unwanted whitespace are everyday tasks. PHP provides purpose-built functions for both.

  • strpos() returns the position (0-based) of the first occurrence, or false if not found.
  • str_contains() (PHP 8+) returns a boolean — cleaner for simple checks.
  • trim() strips whitespace from both ends; ltrim() / rtrim() strip from the left or right only.

Always use strict comparison (!== false) with strpos() because a match at position 0 is falsy.

Example
<?php
$email = '  user@example.com  ';

// Trim whitespace
echo trim($email);            // "user@example.com"
echo ltrim($email);           // "user@example.com  "
echo rtrim($email);           // "  user@example.com"

$haystack = 'The quick brown fox';

// strpos — returns int|false
$pos = strpos($haystack, 'quick');
if ($pos !== false) {
    echo "Found at position: $pos"; // 4
}

// str_contains — PHP 8+ boolean
if (str_contains($haystack, 'fox')) {
    echo 'Fox is present';
}

// str_starts_with / str_ends_with (PHP 8+)
var_dump(str_starts_with($haystack, 'The')); // bool(true)
var_dump(str_ends_with($haystack, 'fox'));   // bool(true)
Pro Tip

Tip: str_contains(), str_starts_with(), and str_ends_with() were added in PHP 8.0 and make intent far clearer than the old strpos() !== false idiom.