0

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 return 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.

2 Answers 2

4

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]);
}
Sign up to request clarification or add additional context in comments.

Comments

3

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").

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.