How to Check Whether a User-Inserted-Word Exceeds the Maximum Limit?

Problem

If a user adds a very long word without any gap (which also conveys no meaning), then it may break the page layout when displaying in the web page. We need a way to determine if any word added by the user doesn’t exceed a maximum limit (for example 35 characters)

Solution

Example:

<?php
$maximum_length = 35;
$user_input = "PHP is a server-side scripting language designed for web development but also used as a general-purpose programming language. PHP is now installed on more than 244 million websites and 2.1 million web servers. Originally created by Rasmus Lerdorf in 1995, the reference implementation of PHP is now produced by The PHP Group. While PHP originally stood for Personal Home Page,it now stands for PHP: Hypertext Preprocessor, a recursive acronymacronymacronymacronymacronymacronym.";
$input_arr = explode(" ", $user_input);
foreach($input_arr as $value){
    if(strlen($value) > $maximum_length)
        echo "The word $value exceeds the maximum word length.";
}
 ?>

Output:

The word acronymacronymacronymacronymacronymacronym. exceeds the maximum word length.

How it Works:

Line 2 Sets the maximum character length of a word as 35
Line 3 Variable $user_input holds the user input.
Line 4 explode() function splits the user input by the space( the first parameter) into words and makes an array. Each element of the array is a word.
Line 5 foreach loop runs through the array.
Line 6 The strlen() function inside the if condition checks whether any word exceeds the maximum length
Line 7 If any word exceeds the maximum limit, the message prints here. The last word of the user input is more than the maximum length and the output in the above shows it.

strlen() function at a glance

(PHP4, PHP5)

Usages:
strlen() function gets the length of a string and returns the number.

Syntax:
strlen(string)

Parameters:

Parameter What it does
string Required Specifies the string to be counted.

Example :

<?php
$string = "Web Development\n";
$length = strlen($string);
echo $length;
?>

Output:
17

  • strlen() function also counts the space and new line characters.
  • If you try to gets the length of an array, it will return NULL and displays warning message.