I'll-Be-Back
I'll-Be-Back

Reputation: 10828

strpos() returns false when needle string contains an invisible / zero-width character

Why it is not returning good?

<?php
$r = "<h3>Welcome</h3>";
if (strpos($r, "​Welcome") !== FALSE) {
    echo "Good";
}
?>

Reproduce by hardcoding the offending unicode character which was destroyed when creating this post:

$r = "<h3>Welcome</h3>";
if (strpos($r, "\u{200C}Welcome") !== FALSE) {
    echo "Good";
}

Upvotes: 1

Views: 306

Answers (3)

DaveRandom
DaveRandom

Reputation: 88647

Your code should work - the logic is fine.

However, there is a funny character in there somewhere - I presume you have copy/pasted this code from somewhere?

When I copy the code off this page into my editor, it complains that there is a character that cannot be represented in my character set, and strpos($r, "​Welcome") becomes strpos($r, "?Welcome").

This does not happen for the input string so they won't match.

Upvotes: 1

middus
middus

Reputation: 9121

Strange, it works for me (see codepad):

<?php
$r = "<h3>Welcome</h3>";
if (strpos($r, "Welcome") !== FALSE) {
    echo "Good";
}

Good

However, I rewrote the string because in your code it contains a hidden character. ;)

Upvotes: 1

mario
mario

Reputation: 145482

Do you see the little box? That is E2 80 8B in UTF-8, the zero-width space.
And that's not present in your source text.


enter image description here

Upvotes: 9

Related Questions