繁体   English   中英

PHP方式在没有数据库查询的情况下执行SQL LIKE匹配?

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

我希望将输入字符串与我的PHP页面匹配,就像SQL(MySQL)中LIKE命令完成匹配一样,以保证其他搜索的一致性。 从(我已经看到但不理解)一些PHP语法包括SQL命令我想知道这是否可能?

这样做的原因是我现在正在实现搜索关键字与数据库中存储在序列化数组中的字段,我必须在PHP中进行反序列化并根据数组的结构进行搜索。 我无法查询表,只需要查询的匹配能力。 否则我需要找到一个替代的匹配例程,这将不一致。 我无法返回并重新构建数据库,因为这不是预期的方式回到规范中。 是的,我需要一个丑陋的黑客,但我正在寻找最优雅的。

如果不可能,我可以使用任何将用户键入的文本作为关键字与存储文本匹配的建议。

编辑(澄清):我的主要问题是我没有彻底掌握LIKE命令如何工作(只是复制代码),并且由于关键字意味着某种程度的模糊性,如果我切换到关键字,我希望保留这种模糊性一个正则表达式。 正如我所说的那样,正则表达式并不是那么好。 我的查询是“LIKE'matmeme%'”

更新

基于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>';
}

你需要的是preg_grep

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

结果是

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

编辑:

用户提供文本,我在后台添加通配符。 我确实使用了一个%。 像'文字%'

这是你如何在正则表达式中指定它

"#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"

此外,请记住对从第三方获得的任何文本使用preg_quote $ regex =“#”。 preg_quote($ text)。 “#一世”; $ res = preg_grep($ regex,$ arr);

我认为你需要preg_match,但这与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."; } 
?>

你的意思是你想要检查输入字符串是否是LIKE var%?

您可以使用strpos(haystack,needle)来匹配%var%。

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

那太难看了。 实际上可能不是最优雅的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM