OMG I understand
OMG I understand

Reputation: 3

How to use preg_match to not allow space in the front and in the end, but allow in between

I have looked around, and I found a lot of tutorials out there. But none of them could help in my case. Here is my script:

if(!preg_match('/^[0-9A-Za-z!@#$%]+$/',$user_name)) {
  echo"bad username";
} 

This code not allow any spaces no matter what if they´re in the front, the end or in between.

I want to allow just between but not in the front and in the end.

Anyone can help me please ?

Upvotes: 0

Views: 3295

Answers (3)

Joe
Joe

Reputation: 28356

The bit you have

[0-9A-Za-z!@#$%]

matches any of those characters the + means one or more. If you want to match those or a space, simply add a space to the list, and place one grouping before and after the existing one, like so:

/^[0-9A-Za-z!@#$%][0-9A-Za-z!@#$% ]+[0-9A-Za-z!@#$%]$/

A side effect of this will be that the username must be at least 3 characters long. If you want to permit smaller usernames, you could split the check:

if(!preg_match('/^[0-9A-Za-z!@#$% ]+$/',$user_name) || preg_match('/^ /',$user_name) || preg_match('/ $/',$user_name)) {

the !preg_match('/^[0-9A-Za-z!@#$% ]+$/',$user_name) makes sure the username only contains approved characters, the preg_match('/^ /',$user_name) checks to see if it starts with a space, and the preg_match('/ $/',$user_name) checks to see if it ends with a space.

If you want to accept what was entered, and automatically remove any leading or trailing spaces, use the trim function.

Upvotes: 3

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89574

You can use this:

/^[0-9A-Za-z!@#$%]++(?>[0-9A-Za-z!@#$%\s]+[0-9A-Za-z!@#$%]+)?+$/

or this if you want to allow empty strings

/^(?>[0-9A-Za-z!@#$%]+(?>[0-9A-Za-z!@#$%\s]*[0-9A-Za-z!@#$%]+)?+)?+$/

Upvotes: 0

Kim Bryan Barcelona
Kim Bryan Barcelona

Reputation: 94

Use trim instead to omit white spaces in the left and right of your text.

<?php
$username = trim($username);

//your code...
?>

Upvotes: 2

Related Questions