What does this pattern match when filtering strings for URLs
Question
What exactly is this line for
preg_replace('#[^0-9a-z]+#i', '-', parent::filter($string))
in the following method in \vendor\magento\framework\Filter\TranslitUrl.php:
public function filter($string)
{
$string = preg_replace('#[^0-9a-z]+#i', '-', parent::filter($string));
$string = strtolower($string);
$string = trim($string, '-');
return $string;
}
The method is used to filter strings which will be used in URLs, and I know that line replaces some strings with -
character. But I don't fully understand what exactly this pattern #[^0-9a-z]+#i
matches.
I will appreciate any hints.
La solution
This pattern #[^0-9a-z]+#i
matches all NOT numeric and NOT alphabetical symbols, in other words it will replace any symbol which is NOT in range 0-9 or a-z with the -
symbol.
The ^
symbol inside group means it is negation (inversion).
The #
symbols detects the start and end of the pattern.
The i
flag says that regular expression should be case insensitive.
In the example string you can see a blue symbols, which will be replaced by that code with the -
symbol:
So a result will be looking like this:
my-mom-says-i-don-t-know-where-it-is
The main purpose of this code is make string a valid URL-string, because you can insert inside the URL-key field whatever you want in any language.
Autres conseils
The #[^0-9a-z]+#i
0-9
-> which indicates numeric values.
a-z
-> which indicated small alphabetical values.
+#
-> will allow #
in url string.
Over all this pattern allow numeric|alphabets|#
type patterns allows.