In this post, we are going to write a program to count the number of integers in a string!. First, we will get the string from the user then we will iterate on each character then find the count of numbers/integers in the string.
Before that let’s write a PHP function which returns the count of integers in the string,
1 2 3 4 5 6 7 8 9 10 11 12 13 |
function find_num_of_integers($string) { //split the strings $chars = str_split($string); $count = 0; foreach($chars as $char) { //check if the character is a number if (is_numeric($char)) { //increment the count $count++; } } return $count; } |
The above function receives a string as a parameter and it returns the number of integers in the string. Go through each and every line in the above function to understand how it works.
Now, let’s see how can we use the above function,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
<?php $alert_class='alert-warning'; $alert_msg = 'Please fill the form'; //if the form is submitted if ($_POST) { //get the string $str = $_POST['string']; if ( strlen($str) > 0 ) { //get the count $string_count = find_num_of_integers($str); //set the output $alert_class = 'alert-success'; $alert_msg = "There are <strong>$string_count</strong> numbers found in this strings!"; } } function find_num_of_integers($string) { //split the strings $chars = str_split($string); $count = 0; foreach($chars as $char) { //check if the character is a number if (is_numeric($char)) { //increment the count $count++; } } return $count; } ?> <!DOCTYPE html> <html lang=""> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>PHP program to count the integers in a string!</title> <!-- Bootstrap CSS --> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <div class="container"> <h1 class="text-center">PHP program to count the integers in a string!</h1> <!-- Output --> <div id="msg"> <div class="alert <?=$alert_class;?>"> <div id="result"><?=$alert_msg;?></div> </div> </div> <!-- our form --> <form action="" method="POST" role="form"> <div class="form-group"> <label for="string">String:</label> <textarea type="text" class="form-control" name="string" id="string"><?=(isset($_POST['first_string'])) ? $_POST['first_string'] : '4568 is a number!';?></textarea> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> </div> </body> </html> |
I have used Bootstrap for a clean and neat look in the above program. Otherwise, it is a simple HTML form that has a textbox and a submit button. After entering the submit button I am using the above PHP function (find_num_of_integers) to get the number of integers in the string. That’s it.
You can see the demo here,