Peter
Peter

Reputation: 1931

How to check if string contain space after each letter

Am trying to check if string has space after each letter, I tried writing below code but it didn't work fine, any idea how I can archive this.

public static function hasWhitespace($text){
    $array = str_split($text);
    $i = 0;
    $check = array();
    foreach($array as $w){
        if ($i % 2 == 1){
            $check[] = empty($w);
        }
        $i++;
    }
    return (array_filter($check) == $check);
}

Usage and Expected output

hasWhitespace("A") true
hasWhitespace("A 3 B") true
hasWhitespace("V 3 A 3 B") true
hasWhitespace("G B A 3 B 9 V") true

hasWhitespace("A3") false 
hasWhitespace("A3 B H 6") false
hasWhitespace("A3B") false

Upvotes: 1

Views: 164

Answers (2)

Nigel Ren
Nigel Ren

Reputation: 57121

One of the problems in your code, is that you check for a space using empty(), which a space isn't empty.

This code uses a loop, but loops over every other character (starting from 1 - the second char) and checks it, if it's not a space then it returns false...

function hasWhitespace($text){
    for ( $i = 1; $i < strlen($text); $i += 2)  {
        if ( $text[$i] != ' ' ) {
            return false;
        }
    }
    return true;
}

Upvotes: 0

anubhava
anubhava

Reputation: 785186

You may use this regex in preg_match to validate your input:

^[\pL\d](?:\h[\pL\d])*$

RegEx Demo

Code:

$re = '/^[\pL\d](?:\h+[\pL\d])*$/';
if (preg_match($re, $str))
   echo "valid";

RegEx Details:

  • ^: Start
  • [\pL\d]: Match a letter or digit
  • (?:\h[\pL\d])*: Match 0 or more single space separated letters or digits
  • $: End

Upvotes: 2

Related Questions