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.
PHP provides numerous built-in functions for working with strings:
strlen()
: Returns the length of a string.$length = strlen("Hello, World!");
strpos()
: Finds the position of the first occurrence of a substring in a string.$position = strpos("Hello, World!", "World");
substr()
: Returns a part of a string.phpCopy code
$substring = substr("Hello, World!", 0, 5); // Output: Hello
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 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.
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.";
}
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!
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);