3

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

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

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

编辑(澄清):我的主要问题是我没有彻底掌握 LIKE 命令的工作原理(只是复制代码),并且由于关键字暗示某种程度的模糊性,我希望如果我切换到这种模糊性保留一个正则表达式。我对正则表达式更好,只是对喜欢不太好。我的查询是“LIKE 'matchme%'”

4

4 回答 4

7

更新

根据 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>';
}
于 2009-02-18T21:22:07.557 回答
4

实际上,您需要的是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"
}

编辑:

用户提供文本,我在幕后添加通配符。我确实使用了 1%。喜欢'文本%'

这是您在正则表达式中指定它的方式

"#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 。$正则表达式 = "#" 。preg_quote($text) 。“#一世”; $res = preg_grep($regex, $arr);

于 2009-02-18T21:22:26.383 回答
0

我认为您需要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."; } 
?>
于 2009-02-18T21:11:11.217 回答
0

您的意思是您希望能够检查输入字符串是否为 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";

那是相当丑陋的。实际上可能不是最优雅的。

于 2009-02-18T21:17:02.513 回答