Regex to add hyphens at specific location of string
I found this regex which works fine if there are no alphabets in 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 string would be sometime mix of alphabets and numbers. What changes I have to do to make it work i开发者_开发问答n both the cases. I have other alternative to iterate a string and add dashes using string functions of PHP but I want to learn how we can achieve it using regular expression.
\w
also allows underscores, if you really only want to allow alphanumeric characters, you'd have to do something like this:
([a-z0-9]{8})([a-z0-9]{4})
And include a i
flag at the end of the regex (after the final /
) to make it case insensitive.
精彩评论