PHP › Strings & String Functions

How do commonly used string functions like strlen, substr, str_replace, and trim help with everyday text processing tasks in PHP?

Intermediate

Answer

PHP provides a large built in library of string functions covering the most common text processing needs, including strlen to find out how many characters a string contains, substr to extract a specific portion of a string starting at a given position, str_replace to find and replace all occurrences of a specific substring with another value, and trim to remove unwanted whitespace from the beginning and end of a string, and combining these simple building blocks together lets you handle a wide variety of everyday text manipulation tasks without needing to write your own custom character by character processing logic.
$input = '  Hello World  ';
$clean = trim($input);
$short = substr($clean, 0, 5);
echo str_replace('Hello', 'Hi', $short);
Real-world example A form processing script trims accidental leading and trailing whitespace from every submitted text field, then checks the resulting cleaned length to ensure it falls within an acceptable range before saving it to the database.

Common follow-ups: What is the difference between strlen and mb_strlen, and when does that difference actually matter?;How do you find the position of a specific substring within a larger string?