OneBite.Dev - Coding blog in a bite size

Check If A String Contains Only Alphanumeric Characters In PHP

Code snippet for how to Check If A String Contains Only Alphanumeric Characters In PHP with sample and detail explanation

Discovering whether a string contains only alphanumeric characters in PHP can be incredibly beneficial for data validation. Ensure the cleanliness and security of your input data by implementing such strategies.

Code Snippet: Check If A String Contains Only Alphanumeric Characters In PHP

function isAlphanumeric($string)
{
    return preg_match('/^[a-z0-9 .\-]+$/i', $string);
}

You can use this function like so:

$string = 'Hello123';
if(isAlphanumeric($string)) {
    echo "The string is alphanumeric";
} else {
    echo "The string is not alphanumeric";
}

Code Explanation: Checking for Alphanumeric Characters in PHP

To check if a string contains only alphanumeric characters in PHP, you can make use of the preg_match() function. This function is a built-in PHP function that performs a regular expression match. It returns 1 if the pattern was found in the string and 0 if it wasn’t.

Let’s dissect the function:

The function isAlphanumeric($string) takes a string as its argument. Inside the function, we call preg_match() with two parameters. The first parameter is the pattern we’re looking for, and the second is the string in which we’re searching.

The pattern '/^[a-z0-9 .\-]+$/i' is a regular expression that matches any string containing one or more alphanumeric characters. Here’s what it means:

  • The caret ^ signifies the start of the string.
  • [a-z0-9 .\-] matches any alphanumeric character. It ranges from a to z, 0 to 9, including whitespace, a period, and a dash.
  • The + means that the string must contain one or more of the alphanumeric characters specified.
  • The dollar sign $ denotes the end of the string.
  • The i at the end, outside of the square brackets, indicates that the match is case-insensitive.

When you want to validate a string, you can call the isAlphanumeric function and pass the string as a parameter. If it returns 1, this means the string is alphanumeric (contains only letters a-z, A-Z, 0-9, whitespace, a period, or a dash). If it returns 0, there are non-alphanumeric characters present in the string.

php