preg_match:应该什么都不匹配?

Is preq_match supposed to return true for testing nothing on something?

$needle = ""; 
$haystack = "test";
$result = preg_match("/" . $needle . "/i", $haystack);

I would expect $result to be 0, but it's 1.

Logically speaking, testing nothing on something should yield nothing ... how does the song go? Nothing from something leaves nothing ... got to have something ... if you want to be with me!.

I didn't want to have to pretest to make sure nothing was something before I tested nothing against something :-). Hmm ... I don't think I could be more confusing if I tried.

There are actually several nothings in the string "test". They are (at a minimum, see my aside below):

<nothing>t<nothing>e<nothing>s<nothing>t<nothing>

That's why you're getting 1 as a result, it's finding that first nothing before the t.

And I suspect that either you're misremembering that song or the bod who wrote it was not an engineer. Nothing from something leaves something (assumng we're talking subtractive operations here).

If it was "something from nothing leaves nothing", that would make more sense but, being the anal-retentive personality type I am, I would have to insist that you can't get something from nothing :-)


As an aside, I'd be interested in what preg_match_all returned for that. Some may think it's 5 (and I suspect it is) but some may argue, from a purely theoretical viewpoint, that there are an infinite number of nothings at each of those points in the string. I would hope the developers of PHP were more practical than that.

Basically, in that usage, preg_match tests for an instance of a given pattern in a string. An empty regular expression is, let's just say, the same as an empty string. Is there an empty string in "test"? Yes; it's before the first t, after the last t, and between each consecutive pair of letters. So the logical result is what you're getting.