Back to course

String Manipulation Functions (Substr, Replace, Trim)

PHP: The Complete 0 to Hero Bootcamp

26. String Manipulation Functions

PHP offers an extensive library of functions for extracting, transforming, and searching strings.

1. Substrings

substr() extracts a part of a string.

php

2. Substring: " . $fox; // Output: fox. ?>

2. Searching and Replacing

FunctionDescription
str_replace(search, replace, subject)Replaces all occurrences of the search string with the replacement string.
strpos(haystack, needle)Finds the position of the first occurrence of a string.

php

3. Replace: " . $new_text; // Output: I love PHP. // Find the position of 'love' $pos = strpos($text, "love"); echo "
4. Position of 'love': " . $pos; // Output: 2 ?>

3. Trimming Whitespace

Whitespace (spaces, tabs, newlines) can cause issues, especially with user input. trim() removes it.

FunctionDescription
trim($str)Removes whitespace from both ends.
ltrim($str)Removes whitespace from the left side.
rtrim($str)Removes whitespace from the right side.

php

5. Cleaned string length: " . strlen($cleaned); // Should be 18, not 24 ?>