开发者

Regex to add hyphens at specific location of string

开发者 https://www.devze.com 2023-04-11 15:19 出处:网络
I found this regex which works fine if there are no alphabets in provided string. $string = \"12522191813381147500333332228323\";

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号