String manipulation is a common task in web development, as you often need to process and format text data. In this lesson, we'll explore PHP's built-in string functions and learn how to use regular expressions for more advanced text processing.

String Functions

PHP provides numerous built-in functions for working with strings:

  1. strlen(): Returns the length of a string.
$length = strlen("Hello, World!");
  1. strpos(): Finds the position of the first occurrence of a substring in a string.
$position = strpos("Hello, World!", "World");
  1. substr(): Returns a part of a string.
phpCopy code
$substring = substr("Hello, World!", 0, 5); // Output: Hello
  1. strtoupper() and strtolower(): Converts a string to uppercase or lowercase.
phpCopy code
$uppercase = strtoupper("Hello, World!"); // Output: HELLO, WORLD!
$lowercase = strtolower("Hello, World!"); // Output: hello, world!

Regular Expressions

Regular expressions are a powerful tool for pattern matching and text processing. PHP provides several functions for working with regular expressions, using the Perl-Compatible Regular Expressions (PCRE) library.

  1. preg_match(): Performs a regular expression match.
$pattern = "/world/i"; // Case-insensitive match for "world"
$string = "Hello, World!";

if (preg_match($pattern, $string)) {
  echo "Match found!";
} else {
  echo "No match found.";
}
  1. preg_replace(): Performs a search and replace using a regular expression.
$pattern = "/world/i"; // Case-insensitive match for "world"
$replacement = "Universe";
$string = "Hello, World!";

$result = preg_replace($pattern, $replacement, $string); // Output: Hello, Universe!
  1. preg_split(): Splits a string by a regular expression.
$pattern = "/[\\s,]+/"; // Split by whitespace or comma
$string = "Hello, World! How are you?";

$words = preg_split($pattern, $string);

Actionable Work: