3v4l.org

run code in 300+ PHP versions simultaneously
<?php $strings = [ '%foo!bar', '@baz', '!bam@bat@bar', '%bee@baa', ]; $field = 'your_column'; $conditionTemplates = [ '&' => '%1$s = ?', '!' => '%1$s IS NULL OR %1$s != ?', '%' => '%1$s LIKE ?', '@' => '%1$s NOT LIKE ?', ]; $needsTrailingWildcard = ['%', '@']; foreach ($strings as $string) { $conditions = []; // reset for demo $params = []; // reset for demo preg_match_all('~([&%@!])([^&%@!]+)~', $string, $matches, PREG_SET_ORDER); foreach ($matches as $match) { $conditions[] = sprintf($conditionTemplates[$match[1]], $field); $params[] = $match[2] . (in_array($match[1], $needsTrailingWildcard) ? '%' : ''); } var_export([implode(' AND ', $conditions), $params]); echo "\n"; }

preferences:
61.13 ms | 402 KiB | 5 Q