开发者

String compare algorithm

I am trying to write some php code to check if a name is contained in another (boolean method).

I am currently using strpos to determine if str1 is in str2, however i want it to be a little smarter. i.e. only check if the str1 exists by itself and not part of another unrelated name/string.

compareStrings(str1,str2)

e.g.

GAP & THISISNOTAGAP //should return false
GAP & IN THE GAP //should r开发者_C百科eturn true
GAP & GAP //shop return true

ROSS & CROSSROADS //should return false
ROSS & ROSS - CHICAGO //should return true

Any ideas if there is a built in function or regex i can use to achieve above? Thanks.


Aasmund is totally correct. I thought I should expand on how it would be done with PHP.

Using: preg_match() and preg_quote().

Its important to use preg_quote so that words with regular expession characters in them don't mess up the test.

Your example tests are included.

<?php
function wordInString($word, $string) {
    return preg_match('/\b'.preg_quote($word, '/').'\b/', $string);
}

$tests = array(
    array('GAP', 'THISISNOTAGAP', false),
    array('GAP', 'IN THE GAP', true),
    array('GAP', 'GAP', true),

    array('ROSS', 'CROSSROADS', false),
    array('ROSS', 'ROSS - CHICAGO', true),
);

foreach($tests as $test) {
    assert(wordInString($test[0], $test[1]) == $test[2]);
}


With regexes, you can use \b to denote a word boundary: \bGAP\b (I hardly know PHP, but I guess you'll have to enter the string literal as "\\bGAP\\b").

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜