4

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 in 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.

1 Answer 1

3

\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.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 and thanks for case insensitive part. Completely missed that!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.