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"; }
based on W6QJ0D
Output for 7.3.0 - 7.3.27, 7.4.0 - 7.4.16, 8.0.0 - 8.0.3
array ( 0 => 'your_column LIKE ? AND (your_column IS NULL OR your_column != ?)', 1 => array ( 0 => 'foo%', 1 => 'bar', ), ) array ( 0 => 'your_column NOT LIKE ?', 1 => array ( 0 => 'baz%', ), ) array ( 0 => '(your_column IS NULL OR your_column != ?) AND your_column NOT LIKE ? AND your_column NOT LIKE ?', 1 => array ( 0 => 'bam', 1 => 'bat%', 2 => 'bar%', ), ) array ( 0 => 'your_column LIKE ? AND your_column NOT LIKE ?', 1 => array ( 0 => 'bee%', 1 => 'baa%', ), )