Ortophius
Ortophius

Reputation: 184

Cant make case-insensitive regular expression in PHP

I cant make a working regexp in php. I'm using i flag at regexp pattern, but it doesnt make a effect on result of my script:

$page = "Test";
$page1 = "test";
var_dump(preg_match("#^test#i", $page));
// int(0)
var_dump(preg_match("#^test#i", $page1));
// int(1)

I really cant realize, where i made a mistake, please help.

Upvotes: 3

Views: 4073

Answers (2)

Sebastian Brosch
Sebastian Brosch

Reputation: 43574

If you want to check case-sensitive you have to remove the i:

$page = "Test";
$page1 = "test";
var_dump(preg_match("/^test/", $page));  // int(0)
var_dump(preg_match("/^test/", $page1)); // int(1)

If you want to check case-insensitive you have to add the i:

$page = "Test";
$page1 = "test";
var_dump(preg_match("/^test/i", $page));  // int(1)
var_dump(preg_match("/^test/i", $page1)); // int(1)

demo: http://ideone.com/Ab9nrs

I tried your code on 3v4l.org and it looks good on the most PHP versions: https://3v4l.org/5UeCu

Upvotes: 7

ashnazg
ashnazg

Reputation: 6688

That code returns "int(1)" for both lines, in PHP 7.1.2 and 5.3.4. Either you are running a PHP version where preg_match has a bug, or you have an invisible control character in one of your two preg_match expressions, and you simply cannot see it.

Upvotes: 0

Related Questions