更新
根据 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>';
}