Search code examples
phpwordpresspluginspreg-matchcontains

preg_match(): Delimiter must not be alphanumeric or backslash with custom field check


I have been working with a plugin and this plugin has a custom field check which doesn't seem to work. Below the code of the plugin used to check a custom field with a certain condition.

<?php if ($custom_field_value != null) {
    if (($set['condition']['value']['operator'] == 'is' && $set['condition']['value']['value'] == $custom_field_value)
    || ($set['condition']['value']['operator'] == 'is_not' && $set['condition']['value']['value'] != $custom_field_value)
    || ($set['condition']['value']['operator'] == 'contains' && preg_match($set['condition']['value']['value'], $custom_field_value)) //The problematic line.
    || ($set['condition']['value']['operator'] == 'does_not_contain' && !preg_match($set['condition']['value']['value'], $custom_field_value))
    || ($set['condition']['value']['operator'] == 'lt' && $set['condition']['value']['value'] < $custom_field_value)
    || ($set['condition']['value']['operator'] == 'le' && $set['condition']['value']['value'] <= $custom_field_value)
    || ($set['condition']['value']['operator'] == 'eq' && $set['condition']['value']['value'] == $custom_field_value)
    || ($set['condition']['value']['operator'] == 'ge' && $set['condition']['value']['value'] >= $custom_field_value)
    || ($set['condition']['value']['operator'] == 'gt' && $set['condition']['value']['value'] > $custom_field_value)) {
        $proceed = true;
    }
}?>

The problem lies within the 'contains' line and give the following error in my debug.log :

PHP Warning: preg_match(): Delimiter must not be alphanumeric or backslash

The check is used to check if a custom field contains either '30', 'text1' or 'text2'.

Now I could be wrong here but I believe I am not using any delimiter here. What could possibly go wrong here?


Solution

  • preg_match expects the paremeters in this order: preg_match( $pattern, $string). Also the pattern needs e.g. forward slashes as said delimiters. So a possible solution would be:

    ...
    || ($set['condition']['value']['operator'] == 'contains'
        &&  preg_match('/' . $custom_field_value . '/', $set['condition']['value']['value'] ))
    || ($set['condition']['value']['operator'] == 'does_not_contain'
        && !preg_match('/' . $custom_field_value . '/', $set['condition']['value']['value'] ))
    ...
    

    If you want to do a simple check, if a string is inside the custom field i would suggest using strpos for performance reasons:

    ...
    || ($set['condition']['value']['operator'] == 'contains'
        &&  strpos($set['condition']['value']['value'],$custom_field_value) > 0)
    || ($set['condition']['value']['operator'] == 'does_not_contain'
        &&  strpos($set['condition']['value']['value'],$custom_field_value) == FALSE)
    ...