Mido Posted July 28, 2010 Share Posted July 28, 2010 Hello, I'm a beginner in regex. Basically, what I want is to match a specified number of integers in a string. Like, : $str="123-456-789" // phone number... I want to check, via preg_match(), whether the string contains [7-15] digits. So, 123-456-789-321-654 would be valid; they contain 20 characters, but only 15 digits, so it's within the interval range. I thought about validating the string then stripping out the hyphens/spaces then count the final filtered version of the string. But I'd rather do them all in one regex pattern. Is there a way to do that? If it wasn't clear enough, please tell which part wasn't. Thanks. Quote Link to comment Share on other sites More sharing options...
cags Posted July 28, 2010 Share Posted July 28, 2010 This is not a task that is best suited to Regex. I'm not even certain it would be possible. Quote Link to comment Share on other sites More sharing options...
cags Posted July 28, 2010 Share Posted July 28, 2010 Well OK, that's a like it is *technically* possible... $pattern = '#^[^0-9]*[0-9][^0-9]*[0-9][^0-9]*[0-9][^0-9]*[0-9][^0-9]*[0-9][^0-9]*[0-9][^0-9]*[0-9][^0-9]*[0-9]?[^0-9]*[0-9]?[^0-9]*[0-9]?[^0-9]*[0-9]?[^0-9]*[0-9]?[^0-9]*[0-9]?[^0-9]*[0-9]?[^0-9]*[0-9]?[^0-9]*$#'; Quote Link to comment Share on other sites More sharing options...
Philip Posted July 28, 2010 Share Posted July 28, 2010 $pattern = '#^[^0-9]*[0-9][^0-9]*[0-9][^0-9]*[0-9][^0-9]*[0-9][^0-9]*[0-9][^0-9]*[0-9][^0-9]*[0-9][^0-9]*[0-9]?[^0-9]*[0-9]?[^0-9]*[0-9]?[^0-9]*[0-9]?[^0-9]*[0-9]?[^0-9]*[0-9]?[^0-9]*[0-9]?[^0-9]*[0-9]?[^0-9]*$#'; Yum! Quote Link to comment Share on other sites More sharing options...
sasa Posted July 29, 2010 Share Posted July 29, 2010 try <?php $str="123-456-789"; preg_match_all('/\d/', $str, $out); $num_of_digits = count($out[0]); echo $num_of_digits; ?> Quote Link to comment Share on other sites More sharing options...
ZachMEdwards Posted August 17, 2010 Share Posted August 17, 2010 or: <?php $str="123-456-789"; echo preg_match_all('/\d/', $str, $out); ?> Quote Link to comment Share on other sites More sharing options...
.josh Posted August 17, 2010 Share Posted August 17, 2010 $count = strlen(preg_replace('~[^0-9]~','',$string)); Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.