Regex Replace and Split
preg_replace swaps the parts of a string that match a pattern for new text. preg_split cuts a string into pieces at each pattern match.
Repeated spaces become one dash
\s matches whitespace, and + after it means one or more in a row. Each run of spaces becomes a single dash.
<?php
$text = "a b c";
echo preg_replace("/\s+/", "-", $text), "\n";Every digit becomes a hash sign
The digit pattern has no plus sign, so each digit is swapped on its own. The second line prints the original string, and it is unchanged.
<?php
$text = "Room 204 has 12 seats";
echo preg_replace("/\d/", "#", $text), "\n";
echo $text, "\n";preg_split cuts on commas and spaces
The brackets hold a set of characters, and the pattern matches a run of any of them. preg_split returns the pieces as an array.
<?php
$text = "red, green blue,white";
$parts = preg_split("/[ ,]+/", $text);
print_r($parts);Example
<?php
$messy = "Hana scored 95 points";
$tidy = preg_replace("/\s+/", " ", $messy);
echo $tidy, "\n";
$words = preg_split("/ /", $tidy);
echo count($words), "\n";Key points
- preg_replace takes three inputs, a pattern, a replacement, and the string to change.
- preg_replace swaps every match in the string, not only the first one.
- preg_split takes a pattern and a string, and it returns an array of pieces.
- A replacement can be any fixed text, like a dash or a hash sign.
- The pieces in the preg_split array keep their left to right order.
In this example, the messy line holds runs of extra spaces. preg_replace swaps each run for one space, and the tidy line prints. preg_split then cuts the tidy line at its single spaces, and count reports 4 words.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does echoing the result of preg_replace("/\d/", "#", "a1b2") print?