In PHP, the preg_replace()
function is used for performing regular expression-based search and replace operations on strings. It allows you to search for a specified pattern (defined using a regular expression) within a string and replace occurrences of that pattern with another string.
Here's an explanation of preg_replace()
:
Syntax:
phppreg_replace(pattern, replacement, subject, limit = -1, &count);
pattern
: The regular expression pattern to search for.replacement
: The string to replace the matched patterns with.subject
: The input string or an array of input strings.limit
(optional): The maximum number of replacements to perform. By default, it's set to -1, which means no limit.count
(optional): If provided, this variable will be filled with the number of replacements performed.
Return Value:
preg_replace()
returns the modified string or an array of modified strings.
Example:
php<?php
// Example using preg_replace()
$inputString = "This is a sample string with extra spaces.";
// Remove multiple spaces with a single space
$trimmedString = preg_replace('/\s+/', ' ', $inputString);
// Display the results
echo "<pre>";
echo "Original String: $inputString\n";
echo "Trimmed String: $trimmedString\n";
?>
In this example:
- The regular expression
'/\s+/'
is used to match one or more whitespace characters (spaces, tabs, newlines). - The replacement string is
' '
, which means a single space. - The
preg_replace()
function replaces sequences of one or more whitespace characters with a single space.
Output:
phpOriginal String: This is a sample string with extra spaces.
Trimmed String: This is a sample string with extra spaces.
This is a simple example, but preg_replace()
becomes more powerful when working with more complex regular expressions. It's commonly used for tasks such as pattern-based substitutions and manipulations in strings.