如何有效地解析两个字符串的字符串?

时间:2012-06-27 15:59:00

标签: php string comparison

如何有效地确定给定字符串是否包含两个字符串?

例如,假设我给了字符串:abc-def-jk-l。此字符串包含两个字符串除以-,或者它不匹配。匹配的可能性是:

Possible Matches for "abc-def-jk-l" :
abc           def-jk-l
abc-def       jk-l
abc-def-jk    l

现在,这是我要匹配的字符串列:

Column I       Column II
-------        -------
1. abc-def     A. qwe-rt
2. ghijkl      B. yui-op
3. mn-op-qr    C. as-df-gh
4. stuvw       D. jk-l

如何有效地检查给定字符串是否与上面列中的两个字符串匹配? (以上是匹配 - 匹配abc-defjk-l

以下是一些例子:

abc-def-yui-op   [MATCH - Matches 1-B]
abc-def-zxc-v    [NO MATCH - Matches 1, but not any in column II.]
stuvw-jk-l       [MATCH - Matches 4-D]
mn-op-qr-jk-l    [Is this a match?]

现在,给定上面的字符串,我如何有效地确定匹配? (效率将是关键,因为列i和ii将在其所尊重的表中的索引列上各有数百万行!)

UPDATE:订单将始终为第i列,然后是第ii列。 (或“不匹配”,这可能意味着它只匹配一列或没有)

这里有一些PHP帮助:

<?php

$arrStrings = array('abc-def-yui-op','abc-def-zxc-v','stuvw-jk-l','stuvw-jk-l');

foreach($arrStrings as $string) {
    print_r(stringMatchCheck($string));
}

function stringMatchCheck($string) {

   $arrI = array('abc-def','ghijkl','mn-op-qr','stuvw');
   $arrII = array('qwe-rt','yui-op','as-df-gh','jk-l');

   // magic stackoverflow help goes here!

    if ()
        return array($match[0],$match[1]);
    else
        return false;

}

?>

2 个答案:

答案 0 :(得分:2)

只需使用PHP的strpos()即可。循环直到您使用$arrI$string的{​​{1}}中找到条目,并对strpos()执行相同操作。

有关$arrII的更多信息:http://php.net/manual/en/function.strpos.php

编辑:

为了帮助您了解我在说什么,这是您的功能:

strpos()

答案 1 :(得分:1)

为了提高效率,不是遍历每列中的每个条目,而是将字符串拆分为尽可能多的不同单词并搜索每个单词组合。基本上你提到的可能匹配。

$words = explode("-", $string);
$end = count($words) - 1;

for ( $i = 1; $i < $end; $i++ ) {
    $partOne = array_slice($words, 0, $i);
    $parttwo = array_slice($words, $i);
    $wordOne = implode("-" , $partOne);
    $wordTwo = implode("-" , $partTwo);

    /* SQL to select $wordOne and $wordTwo from the tables */
}
相关问题