Anchored regex without fear
preg_match
Function preg_match tests a string against a pattern and returns 1 on success and 0 on failure. Anchors lock the test to the full string so partial hits do not pass.
Caret marks the start and dollar marks the end, so a pattern with both checks the whole value from first to last character.
$text = "order-42";
if (preg_match("/^order-[0-9]+$/", $text, $m)) {
echo $m[0];
}
preg_replace
Function preg_replace returns a new string with every match replaced. The original value stays unchanged and the result holds the edits.
Use a character class for digits or letters when the exact text varies but the shape stays the same.
$text = "hi 2026-10-06";
echo preg_replace("/[0-9]+/", "#", $text);
Delimiters
Every pattern needs delimiters around the core expression. The common choice is / but hash and tilde work the same way.
Pick a delimiter that does not appear in the pattern itself. That choice keeps the pattern short and easy to read.
$text = "path to file";
var_dump((bool) preg_match("#^path#", $text));
var_dump((bool) preg_match("~file$~", $text));
Escape with preg_quote
Never paste user text straight into a pattern because dots and brackets have special meaning. Function preg_quote escapes every special character for you.
Pass the delimiter as the second argument so it gets escaped as well, then add anchors around the quoted part.
$word = "price (usd)";
$pattern = "/^" . preg_quote($word, "/") . "$/";
$text = "price (usd)";
var_dump((bool) preg_match($pattern, $text));
Next: Multibyte strings
Article author: Arthur Isaev