preg_replace() / preg_split() Since: PHP 4(2000)
Uses regular expressions to replace or split strings. You can replace matched parts with another string, or split a string using a pattern as a delimiter.
Syntax
// Replaces parts of a string that match the pattern. preg_replace($pattern, $replacement, $subject, $limit); // Replaces matched parts using a callback function. preg_replace_callback($pattern, $callback, $subject, $limit); // Splits a string using the pattern as a delimiter. preg_split($pattern, $subject, $limit, $flags); // Filters array elements using a regular expression. preg_grep($pattern, $array, $flags);
Function List
| Function | Description |
|---|---|
| preg_replace($pattern, $replacement, $subject) | Replaces parts of the string that match the regular expression with the replacement string. You can reference capture groups in the replacement using $1 or ${1}. |
| preg_replace_callback($pattern, $callback, $subject) | Calls a callback function for each match and uses the return value as the replacement. Used for dynamic replacement logic. |
| preg_split($pattern, $subject, $limit) | Splits a string using a regular expression pattern as the delimiter and returns an array. Provides more flexible splitting than explode(). |
| preg_grep($pattern, $array) | Filters array elements using a regular expression and returns an array containing only the matching elements. |
Return Value
preg_replace() and preg_replace_callback() return the modified string. If $subject is an array, an array is returned. preg_split() returns an array of the split strings. preg_grep() returns an array of matching elements. On error, all functions return null.
Sample Code
<?php
// Basic replacement
echo preg_replace("/PHP/", "PHP8", "PHP is popular."); // Outputs 'PHP8 is popular.'
// Case-insensitive replacement
echo preg_replace("/hello/i", "Hi", "Hello World"); // Outputs 'Hi World'
// Replacement using capture groups
$date = "2025/04/15";
echo preg_replace("/(\d{4})\/(\d{2})\/(\d{2})/", "$1-$2-$3", $date); // Outputs '2025-04-15'
// Practical example: convert date format
$date = "2025-04-15";
echo preg_replace("/(\d{4})-(\d{2})-(\d{2})/", "$2/$3/$1", $date); // Outputs '04/15/2025'
// Remove HTML tags
$html = "<p>Text</p><br><strong>Bold</strong>";
echo preg_replace("/<[^>]+>/", "", $html); // Outputs 'TextBold'
// Collapse consecutive whitespace into a single space
$text = "Hello World here";
echo preg_replace("/\s+/", " ", $text); // Outputs 'Hello World here'
// Dynamic replacement with preg_replace_callback()
$text = "Item A: $15, Item B: $23";
$result = preg_replace_callback("/\$(\d+)/", function($matches) {
$price = $matches[1];
return "$" . number_format($price) . " (tax incl. $" . number_format($price * 1.1) . ")";
}, $text);
echo $result; // Outputs 'Item A: $15 (tax incl. $16.5), Item B: $23 (tax incl. $25.3)'
// Practical example: expand template variables with preg_replace_callback()
$template = "Hello, {{name}}. Your appointment on {{date}} has been confirmed.";
$vars = ["name" => "Alice", "date" => "April 15"];
$result = preg_replace_callback("/\{\{(\w+)\}\}/", function($matches) use ($vars) {
return $vars[$matches[1]] ?? $matches[0]; // Leave undefined variables as-is.
}, $template);
echo $result; // Outputs 'Hello, Alice. Your appointment on April 15 has been confirmed.'
// Flexible splitting with preg_split()
$csv = "apple, orange, banana ,grape";
$fruits = preg_split("/\s*,\s*/", $csv);
print_r($fruits); // Splits on commas with surrounding whitespace, resulting in a 4-element array.
// Split on multiple delimiters
$text = "PHP;JavaScript,Python|Ruby";
$languages = preg_split("/[;,|]/", $text);
print_r($languages); // Results in an array of 4 language names.
// Filter an array with preg_grep()
$files = ["index.php", "style.css", "app.js", "config.php", "readme.md"];
$php_files = preg_grep("/\.php$/", $files);
print_r($php_files); // Outputs ["index.php", "config.php"]
// Use PREG_GREP_INVERT as an exclusion filter
$non_php = preg_grep("/\.php$/", $files, PREG_GREP_INVERT);
print_r($non_php); // Outputs all non-PHP files.
Notes
preg_replace() is a regex-based replacement function. You can reference capture groups in the replacement string using $1, $2, etc., which is useful for tasks like reformatting dates. For simple fixed-string replacements, str_replace() is faster.
preg_replace_callback() is useful when the replacement string needs to be generated dynamically based on each match. The callback receives an array in the same format as $matches in preg_match(): $matches[0] is the full match, and $matches[1] and beyond are the capture groups.
preg_split() is more flexible than explode() when you need to split on multiple delimiter types or strip surrounding whitespace at the same time. preg_grep() is specialized for filtering arrays and can be used as an exclusion filter with the PREG_GREP_INVERT flag. For pattern matching, use preg_match() / preg_match_all().
If you find any errors or copyright issues, please contact us.