如何有效地确定给定字符串是否包含两个字符串?
例如,假设我得到了字符串: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-def
和jk-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;
}
?>
只需使用 PHP 的strpos()
即可。循环,直到使用 strpos()
从 $arrI
中找到$string
中的条目,并对$arrII
执行相同的操作。
更多信息 strpos()
: http://php.net/manual/en/function.strpos.php
编辑:
为了帮助您了解我在说什么,这是您的函数:
function stringMatchCheck($string) {
$arrI = array('abc-def','ghijkl','mn-op-qr','stuvw');
$arrII = array('qwe-rt','yui-op','as-df-gh','jk-l');
$match = array(NULL, NULL);
// get match, if any, from first group
for ($i=0; $i<count($arrI) && !is_null($match[0]); $i++) {
if (strpos($string,$arrI[$i]) !== false) {
$match[0]=$arrI[$i];
}
}
if (!is_null($match[0])) {
// get match, if any, from second group group
for ($i=0; $i<count($arrII) && !is_null($match[1]); $i++) {
if (strpos($string,$arrII[$i]) !== false) {
$match[1]=$arrII[$i];
}
}
}
if (!is_null($match[0]) && !is_null($match[1])) {
return $match;
} else {
return false;
}
}
为了提高效率,与其遍历每列中的每个条目,不如将字符串拆分为尽可能多的不同单词并搜索每个单词组合。 基本上你提到的可能的匹配。
$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 */
}