Skip to content
Advertisement

How to call commas separated values within preg_match

$values = 'apple,orange,banana,mango';

public static function likecheck( $data) {
    if(preg_match("/( apple | orange | banana | mango )/i", $data) === 1) {
        return true; 
    }
}

I want my $values to be called dynamically within preg_match as apple | orange | banana | mango

Advertisement

Answer

Just explode by comma and ‘glue’ all together with implode

$values = 'apple,orange,banana,mango';
$regexValues = implode(' | ', explode(',', $values));

if(preg_match("/ $regexValues /i", $data) === 1) {
    return true; 
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement