How to check if string contains only a spaces in PHP?
In this post, we help you how to check if string contains only a spaces in PHP.
1. Code snippet
<?php
function haveOneSpaceBetween($str){
$str = trim($str);
$firstAppear = strpos($str, " ");
$lastAppear = strrpos($str, " ");
if ($firstAppear && $firstAppear == $lastAppear) {
return true;
}
return false;
}
$str = "soltuts.com Tips,tricks,codesnippets";
$str = haveOneSpaceBetween($str);
var_dump($str);
?>
Output
bool(true)
2. Example
Input:
$str = "soltuts.com Tips,tricks,codesnippets"; $str = "soltuts.com Tips, tricks, code snippets";
Output:
bool(true) bool(false)
3. Download this Example from Github
Have a nice day!
SolTuts 🙂