If string contains number, save number in variable?
So heres what i have. I have an array of $_POST
elements and some end with a number, some do not. So whatI have already is:
foreach ($_POST as $field_name => $value){ }
What id like to d开发者_运维问答o it put an if statement within the foreach, and say 'if $field_name contains a number, save that number in a variable $num'. And then foreach $field_name that contains that same $num, do this...
Im pretty clear on the concept, but not the actual code. The first step would be to determine if the the field contains a digit 1-9 within it. Any suggestions?
Use preg_match
!
if( preg_match('/\d+/', $field_name, $matches) ) {
$num = $matches[0];
// Do other stuff here
}
(Edit: simplified)
Better do it without regular expression its much faster!!
if (strcspn($_Post[$i], '0123456789') != strlen($_Post[$i])){}
no need to start the regularexpression engine...
You can try this:
preg_match_all('/[1-9]/', $field_name, $matches);
$matches should contain now all number occurencies stored in array. Proccess it how you prefer :D
精彩评论