根据tomalak的评论和OIS使用preg_grep的绝妙想法,这可能更符合最终解决方案的要求。
<?PHP
function convertLikeToRegex( $command )
{
return "/^" . str_replace( '%', '(.*?)', preg_quote( $command ) ) . "$/s";
}
function selectLikeMatches( $haystack, $needle )
{
return preg_grep( convertLikeToRegex( $needle ), $haystack );
}
$likeClauses = array(
'%foo'
,'foo%'
,'%foo%'
);
$testInput = array(
'foobar'
,'barfoo'
,'barfoobaz'
);
foreach ( $likeClauses as $clause )
{
echo "Testing $clause:";
echo '<pre>';
print_r( selectLikeMatches( $testInput, $clause ) );
echo '</pre>';
}
这是您追求的目标吗?
<?PHP
function convertLikeToRegex( $command )
{
return "/^" . str_replace( '%', '(.*?)', $command ) . "$/s";
}
$likeClauses = array(
'%foo'
,'foo%'
,'%foo%'
);
$testInput = array(
'foobar'
,'barfoo'
,'barfoobaz'
);
foreach ( $testInput as $test )
{
foreach ( $likeClauses as $clause )
{
echo "Testing '$test' against like('$clause'): ";
if ( preg_match( convertLikeToRegex( $clause ), $test ) )
{
echo 'Matched!';
} else {
echo 'Not Matched!';
}
echo '<br>';
}
echo '<hr>';
}