Khalid
Khalid

Reputation: 77

Matching only Arabic and English Alphanumeric with one space allowed only

I have got a forum site and I am currently working on the final piece, the registration form and I want to validate the username. It should only contain Arabic and English alphanumerics and a maximum of one space between words.

I've got the english alphanumeric part working but not the Arabic nor the double spaces.

I am using the preg_match() function to match the username input with the RegEX.

What I currently have:

!preg_match('/\p{Arabic}/', $username) && !preg_match('/^[A-Za-z0-9]$/')
//this is currently inside and if statement, so if they both don't match then it is false.

Upvotes: 1

Views: 2311

Answers (1)

chris85
chris85

Reputation: 23880

You should put the unicode properties inside your regular regex because this can all be done with 1 regex. You also need to quantify that character class otherwise you only allow 1 character. This regex should do it.

^[\p{Arabic}a-zA-Z\p{N}]+\h?[\p{N}\p{Arabic}a-zA-Z]*$

Use the u modifier in PHP so unicode works as expected.

PHP Usage:

preg_match('/^[\p{Arabic}a-zA-Z\p{N}]+\h?[\p{N}\p{Arabic}a-zA-Z]*$/u', $string);

Demo: https://regex101.com/r/fsRchS/2/

Upvotes: 4

Related Questions