PHP way to execute SQL LIKE matching without a database query?

大兔子大兔子 提交于 2019-12-05 21:05:18

Update

Based on tomalak's comment and OIS's brilliant idea to use preg_grep, this might be something more along the lines of a final solution for you.

<?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>';
}

Original Post Below

Is this along the lines of what you're after?

<?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>';
}

What you need is preg_grep actually.

$arr = array("tstet", "duh", "str");
$res = preg_grep("#st#i", $arr); //i for case insensitive
var_dump($res);

results in

array(2) {
  [0]=>
  string(5) "tstet"
  [2]=>
  string(3) "str"
}

edit:

the user supplies the text, I add the wildcards behind the scenes. I do use one %. LIKE 'text%'

here is how you specify it in regex

"#st#i"  regex is the same as in sql "%st%"
"#^st#i" regex is the same as in sql "st%"
"#st$#i" regex is the same as in sql "%st"

Also, remember to use preg_quote on any text you get from a third party. $regex = "#" . preg_quote($text) . "#i"; $res = preg_grep($regex, $arr);

I'd think you'd need preg_match but that's not exactly the same behavior as a LIKE.

<?php // The "i" after the pattern delimiter indicates a case-insensitive search 
if (preg_match("/php/i", "PHP is the web scripting language of choice.")) {
    echo "A match was found."; 
} else {
    echo "A match was not found."; } 
?>

Do you mean you want to be able to check if the input string is LIKE var% ?

You could use strpos(haystack, needle) to match %var%.

if( strpos($source, "var") == 0 ) echo "matches var%";
if( strlen($source) - (strpos($source, "var")) == strlen("var") ) echo "matches %var";

That is pretty ugly. And actually probably not the most elegant.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!