<?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";
}
- Output for 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.33, 8.2.0 - 8.2.29, 8.3.0 - 8.3.25, 8.4.1 - 8.4.12
- 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%',
),
)
preferences:
151.97 ms | 408 KiB | 5 Q