-4

This is my first try at regex in PHP. I would like to use regex in PHP to match sentences that contains two set of words. I have tested it like below but it's not working

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

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

I am getting an error message in PHP.

Warning: preg_match(): Unknown modifier [
Cryssie
  • 3,047
  • 10
  • 54
  • 81
  • 4
    `$regex= "/(red|green|round|sweet)[^.]*(apple|apples)/";` - Plus, if you tested as you said what you posted, should have thrown a parse error to start. – Funk Forty Niner Oct 30 '14 at 02:51
  • @Fred-ii- I tested the regex and it works. Just not in php. For some reasons it's complaining about the [ ] – Cryssie Oct 30 '14 at 02:53
  • Your posted question is missing semi-colons on two lines, missing quotes and identifier for the first. Which I tested and working. – Funk Forty Niner Oct 30 '14 at 02:55

2 Answers2

2

PHP regex must separate character.

$regex = '/(red|green|round|sweet)[^.]*(apple|apples)/';

/ is separate character in this case.

alu
  • 456
  • 2
  • 7
1

As I said, this is tested and working, where you left out the quotes and identifiers for the first line and missing semi-colons on two lines.

<?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!!!';
}
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141