How do I check whether input string contains any spaces?
Why use a regex?
name.contains(" ")
That should work just as well, and be faster.
PHP check if string contains space between words (not at beginning or end)
You can verify that the trimmed string is equal to the original string and then use strpos
or str_contains
to find a space.
// PHP < 8
if ($str == trim($str) && strpos($str, ' ') !== false) {
echo 'has spaces, but not at beginning or end';
}
// PHP 8+
if ($str == trim($str) && str_contains($str, ' ')) {
echo 'has spaces, but not at beginning or end';
}
Some more info if you're interested
If you use strpos()
, in this case, you don't have to use the strict comparison to false
that's usually necessary when checking for a substring that way. That comparison is usually needed because if the string starts with the substring, strpos()
will return 0
, which evaluates as false
.
Here it is impossible for strpos()
to return 0
, because the initial comparison$str == trim($str)
eliminates the possibility that the string starts with a space, so you can also use this if you like:
if ($str == trim($str) && strpos($str, ' ')) { ...
If you want to use a regular expression, you can use this to check specifically for space characters:
if (preg_match('/^[^ ].* .*[^ ]$/', $str) { ...
Or this to check for any whitespace characters:
if (preg_match('/^\S.*\s.*\S$/', $str) { ...
I did some simple testing (just timing repeated execution of this code fragment) and the trim/strpos solution was about twice as fast as the preg_match solution, but I'm no regex master, so it's certainly possible that the expression could be optimized to improve the performance.
Check if space is in a string
==
takes precedence over in
, so you're actually testing word == True
.
>>> w = 'ab c'
>>> ' ' in w == True
1: False
>>> (' ' in w) == True
2: True
But you don't need == True
at all. if
requires [something that evalutes to True or False] and ' ' in word
will evalute to true or false. So, if ' ' in word: ...
is just fine:
>>> ' ' in w
3: True
Related Topics
Comparing Two Json Arrays and Get Not Matching Values
How to Change Div Order in JavaScript
Resize a Base-64 Image in JavaScript Without Using Canvas
Regex to Match 2 Different Words in a String
Count Total Number of Checkboxes What Are Checked and Show on Page Via Js
React State Change Not Causing Re-Render
Setting the Value of a Checkbox Input If Not Checked
How to Pass JavaScript Confirm Variable to PHP Variable
How to Add a Simple Onclick Event Handler to a Canvas Element
Finding the Symmetric Difference Between Two Arrays
Firebase.Firestore() Is Not a Function When Trying to Initialize Cloud Firestore
How to Fetch Url of Current Tab in My Chrome Extension Using JavaScript
How to Block +,-,E in Input Type Number
Json to CSV Flattening Nested Json
Lodash Group by Multiple Properties If Property Value Is True
Replace All Chars With #, Except for Last 4
Escaping Apostrophe (Single Quote) Character in JavaScript and HTML