Core\Regex::quote
Core\Regex::quote(string $text): stringCore\Regex::quote( string $text, ): string
Puts a \ before every character that has a special meaning in a pattern, such as ., + or (. The result is a pattern that matches the original text exactly, and nothing else. A text with no special characters is returned unchanged.
Use it when a pattern must contain a text that you did not write yourself, such as a search that a person typed. A text from a request is tainted (it came from outside the program), and a tainted text does not compile as a pattern. The result of Core\Regex::quote is allowed as a pattern.
The examples show a text matched exactly, a quoted text inside a bigger pattern, and a search for what a person typed.
Parameters
$textstringThe text to match exactly.
Return value
Returns string. The escaped pattern. A text with no special characters is returned unchanged. & and ~ are escaped, and !, :, <, =, > and / are not.
Examples
Match a text exactly
<?nvs// Shows how to turn a text into a pattern that matches exactly that text.
// `+` has a special meaning in a pattern. `Core\Regex::quote` puts a `\` before it.// This prints "1\+1=2".string $pattern = Core\Regex::quote('1+1=2');echo $pattern, "\n";
// The quoted pattern matches the text "1+1=2", so this prints "yes".echo Core\Regex::matches('We know that 1+1=2.', $pattern) ? 'yes' : 'no', "\n";
// Without `quote`, `1+` means "one or more 1". This prints "yes" for the text "11=2".echo Core\Regex::matches('11=2', '1+1=2') ? 'yes' : 'no', "\n";1\+1=2yesyesA quoted text inside a bigger pattern
<?nvs// Shows how to put a quoted text inside a bigger pattern.
string $version = 'v2.1';
// The quoted text is "v2\.1", so the `.` matches only a dot. `(\d+)` after it// matches the patch number. This prints "patch 7".Core\Regex\Pattern $release = Core\Regex::compile('^' . Core\Regex::quote($version) . '\.(\d+)$');?Core\Regex\Match $found = Core\Regex::match('v2.1.7', $release);echo 'patch ', $found?->group(1) ?? 'none', "\n";
// "v231.7" has a "3" where the dot should be, so there is no match. This prints "patch none".$found = Core\Regex::match('v231.7', $release);echo 'patch ', $found?->group(1) ?? 'none', "\n";patch 7patch noneSearch for what a person typed
<?nvs// Shows how to search a list of product names for the text that a person typed.
array<string> $products = ['C++ (2nd Ed.)', 'C Primer', 'Learning C++ in a week'];string $typed = 'c++';
// `quote` makes the typed text match exactly, and `caseInsensitive` ignores upper// and lower case. This prints the two names that contain "C++".Core\Regex\Pattern $search = Core\Regex::compile(Core\Regex::quote($typed), { caseInsensitive: true });foreach ($products as string $name) { if (Core\Regex::matches($name, $search)) { echo $name, "\n"; }}C++ (2nd Ed.)Learning C++ in a week