dbj44
dbj44

Reputation: 1998

PHP: How do I test for whitespace at the beginning and end of a string?

How do I test for whitespace at the beginning and end of a string?

I don't want to remove spaces, I just want a boolean TRUE or FALSE returned if they exist.

Thanks.

Upvotes: 1

Views: 1534

Answers (6)

Indra Kumar S
Indra Kumar S

Reputation: 2934

Check like this

  if (substr($str, -1) == " " || $str[0] == " " ) {

    }

Upvotes: 1

p0d4r14n
p0d4r14n

Reputation: 681

<?php
$test = 'test ';

if (strpos($test, ' ') === 0 || strpos($test, ' ') === strlen($test)-1) {
    return true;
}
?>

EDIT: See darkbees explaination

Upvotes: 1

RST
RST

Reputation: 3925

$string = <your string>;
$ns_string = trim($string);
$spaces_present = ($ns_string == $string) ? false : true;

in shorter notation

$space_present = ($string != trim($string));

Upvotes: 7

axiac
axiac

Reputation: 72226

ctype_space($str[0]) || ctype_space(substr($str, -1))

Upvotes: 1

andrew
andrew

Reputation: 9583

simple regex

preg_match("~(^\s|\s$)~", $subject);

Upvotes: 0

Rizier123
Rizier123

Reputation: 59681

This should work for you:

<?php

    $str = "test";

    if($str[0] == " "|| $str[strlen($str)-1] == " ")
        echo "space at the start or the end";

?>

Upvotes: 4

Related Questions