I'm creating a password validator which takes any character but whitespaces and with at least 6 characters.
After searching the best I came up is this is this example: What is the regular expression for matching that contains no white space in between text?
It disallows any spaces inbetween but does allow starting and ending with a space. I want to disallow any space in the string passed.
I tried this but it doesn't work:
if (preg_match("/^[^\s]+[\S+][^\s]{6}$/", $string)) {
return true;
} else {
return false;
}
Thanks.
You can easily trim unnecessary whitespace from the start and the end of a string or the lines in a text file by doing a regex search-and-replace. Search for ^[ \t]+ and replace with nothing to delete leading whitespace (spaces and tabs). Search for [ \t]+$ to trim trailing whitespace.
You can match a space character with just the space character; [^ ] matches anything but a space character.
This is important since for status updates on social media, the white space between words and characters is counted for the overall character count as well.
Space, tab, line feed (newline), carriage return, form feed, and vertical tab characters are called "white-space characters" because they serve the same purpose as the spaces between words and lines on a printed page — they make reading easier.
Something like this:
/^\S{6,}\z/
Can be quoted like:
preg_match('/^\S{6,}\z/', $string)
All answers using $
are wrong (at least without any special flags). You should use \z
instead of $
if you do not want to allow a line break at the end of the string.
$
matches end of string or before a line break at end of string (if no modifiers are used)\z
matches end of string (independent of multiline mode)From http://www.pcre.org/pcre.txt:
^ start of subject
also after internal newline in multiline mode
\A start of subject
$ end of subject
also before newline at end of subject
also before internal newline in multiline mode
\Z end of subject
also before newline at end of subject
\z end of subject
The simplest expression:
^\S{6,}$
^
means the start of the string\S
matches any non-whitespace character{6,}
means 6 or more$
means the end of the string
In PHP, that would look like
preg_match('/^\S{6,}$/', $string)
Edit:
>> preg_match('/^\S{6,}$/', "abcdef\n")
1
>> preg_match('/^\S{6,}\z/', "abcdef\n")
0
>> preg_match('/^\S{6,}$/D', "abcdef\n")
0
Qtax
is right. Good call! Although if you're taking input from an HTML <input type="text">
you probably won't have any newlines in it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With