ehime
ehime

Reputation: 8375

Word boundary matching empty strings

I'm currently trying to get a match on an empty string in PHP, this current run through should match not and empty '' but I can only seem to get it to match not for some reason? Could someone tell me what I'm doing wrong?

preg_match('/^\bnot|$/', 'not', $matches);
print_r($matches);  // array(0 => 'not') // correct

preg_match('/^\bnot|$/', '', $matches);
print_r($matches);  // array(0 => '') // maybe right ?

preg_match('/^\bnot|$/', 'foo', $matches);
print_r($matches);  // array(0 => '') // deff messed up

Upvotes: 0

Views: 195

Answers (2)

Rottingham
Rottingham

Reputation: 2604

If you want to determine if a string is empty, don't use preg_match. Use strlen();

$string = '';
$strlen = strlen($string);
if ($strlen === 0) {
    // $string is empty
}

Upvotes: 0

hwnd
hwnd

Reputation: 70732

That's because you are trying to match an empty string incorrectly. Your regular expression should be.

^$|pattern

And with \b (word boundary), this matches from a \w (word character) to a \W (non word character). It is in fact a zero-width match (empty string) but only matches those strings at specific places in a word boundary

Upvotes: 1

Related Questions