警告:preg_match():PHP中的未知修饰符

时间:2014-10-30 02:49:20

标签: php regex

这是我在PHP中使用正则表达式的第一次尝试。我想在PHP中使用正则表达式来匹配包含两组单词的句子。我已按下面的方式对其进行了测试,但它无法正常工作

$regex= (red|green|round|sweet)[^.]*(apple|apples)    
$sentence = "I have two red apples."

if(preg_match($regex, $sentence)) 
{
    echo 'MATCH!!!';
} else {
    echo 'No MATCH!!!';
}

我在PHP中收到错误消息。

Warning: preg_match(): Unknown modifier [

2 个答案:

答案 0 :(得分:2)

PHP正则表达式必须分开字符。

$regex = '/(red|green|round|sweet)[^.]*(apple|apples)/';
在这种情况下,

/是单独的字符。

答案 1 :(得分:1)

正如我所说,这是经过测试和运作的,你遗漏了第一行的引号和标识符以及两行上缺少的分号。

<?php
$regex= "/(red|green|round|sweet)[^.]*(apple|apples)/";
$sentence = "I have two red apples.";

if(preg_match($regex, $sentence))
{
    echo 'MATCH!!!';
} else {
    echo 'No MATCH!!!';
}