<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Count Digits</title>
</head>
<body>
<h1>Count Digits in Input</h1>
<form method="post" action="">
<label for="inputText">Enter text:</label>
<input type="text" id="inputText" name="inputText" required>
<input type="submit" value="Count Digits">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the input value
$inputText = $_POST['inputText'];
// Initialize the digit count
$digitCount = 0;
// Count the number of digits
for ($i = 0; $i < strlen($inputText); $i++) {
if (is_numeric($inputText[$i])) {
$digitCount++;
}
}
// Display the result
echo "<h2>Result:</h2>";
echo "<p>Number of digits: $digitCount</p>";
}
?>
</body>
</html>
Explanation:
1. HTML Form: The form uses the `POST` method to send data to the same script.
2. PHP Script: The PHP block processes the form submission:
- Retrieve Input: It gets the input text from the form using `$_POST['inputText']`.
- Count Digits: A loop goes through each character of the input text, checking if it is a numeric character using `is_numeric()`. If it is, it increments the `$digitCount` variable.
- Display Result: The number of digits is displayed below the form.
Post a Comment
If you have any doubts, Please let me know
Thanks!