super-powers/src/ce8cf834-6bac-44fb-941c-861.../code.power

41 lines
1.1 KiB
Plaintext
Raw Normal View History

2023-04-15 14:49:41 +00:00
/**
* Making namespace safe
*
2023-10-04 18:23:30 +00:00
* @param string $string The namespace string you would like to make safe
2023-04-15 14:49:41 +00:00
*
2023-10-04 18:23:30 +00:00
* @return string on success
2023-04-15 14:49:41 +00:00
* @since 3.0.9
*/
2023-10-04 18:23:30 +00:00
public static function safe(string $string): string
2023-04-15 14:49:41 +00:00
{
2023-10-04 18:23:30 +00:00
// Remove leading and trailing backslashes
$string = trim($string, '\\');
// Split the string into namespace segments
$segments = explode('\\', $string);
foreach ($segments as &$segment)
2023-04-15 14:49:41 +00:00
{
2023-10-04 18:23:30 +00:00
// Check if segment starts with a number
if (preg_match("/^\d/", $segment))
2023-04-15 14:49:41 +00:00
{
2023-10-04 18:23:30 +00:00
// Extract the starting number(s)
preg_match("/^\d+/", $segment, $matches);
if (isset($matches[0]))
{
$numberWord = StringHelper::numbers($matches[0]);
$segment = str_replace($matches[0], $numberWord, $segment);
}
2023-04-15 14:49:41 +00:00
}
// Transliterate string TODO: look again as this makes it lowercase
2023-10-04 18:23:30 +00:00
// $segment = StringHelper::transliterate($segment);
2023-04-15 14:49:41 +00:00
2023-10-04 18:23:30 +00:00
// Make sure segment only contains valid characters
$segment = preg_replace("/[^A-Za-z0-9]/", '', $segment);
2023-04-15 14:49:41 +00:00
}
2023-10-04 18:23:30 +00:00
// Join the namespace segments back together
return implode('\\', $segments);
}