I hate to ask that kind of question because the answer is either 'I am stupid' or 'there is strange problem with my computer'... (and the first one is probably the right one) But I am stuck on that :
$matches = preg_grep("(.+)","ThisIsATest");
error_log(count($matches), 3, "php.log");
The log gives me 0
, no matter what I give as a pattern... I can't understand why this $matches
variable is always empty !
preg_grep
不是用于搜索字符串,而是用于搜索字符串数组...您可能应该改用preg_match
。
This is the error you should be getting:
preg_grep() expects parameter 2 to be array, string given
This is a way to return one match (and you will only have 1 in this case) with preg_match
:
preg_match("(.+)","ThisIsATest", $matches);
print_r($matches);
See IDEONE demo
To access the value using $matches[0]
, you need to use preg_match_all
:
preg_match_all("(.+)","ThisIsATest", $matches);
print_r($matches[0]);
See another demo
It seems that you are just using the wrong method:
if (preg_match('/(.+)/', "ThisIsATest")) {
# Successful match
} else {
# Match attempt failed
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.