A regular expression to add a hyphen at a specific point in a string

I found this regex that works great if there are no alphabets in the provided string.

$string = "12522191813381147500333332228323"; echo $formattedString = preg_replace("/^(\d{8})(\d{4})(\d{4})(\d{4})(\d{12})$/", "$1-$2-$3-$4-$5", $string); 

My input line will someday be a combination of alphabets and numbers. What changes should I make to make it work in both cases. I have another alternative to iterating over a string and adding dashes using PHP string functions, but I want to find out how we can achieve this using a regular expression.

+4
source share
1 answer

\w also allows you to underline, if you really want only alphanumeric characters, you need to do something like this:

 ([a-z0-9]{8})([a-z0-9]{4}) 

And include the i flag at the end of the regular expression (after the final / ) to make the case insensitive.

+3
source

All Articles