Reputation: 1477
my case is like this:
<?php
$var1 = "Top of British";
$var2 = "Welcome to British, the TOP country in the world";
$var1 = strtolower($var1);
$var2 = strtolower($var2);
if (strpos($var1, $var2) !== FALSE) {
echo "TRUE";
}
?>
its not working, how do i detect the TOP or British is exist on both string?
Upvotes: 1
Views: 632
Reputation: 17661
Remove the punctuation from the strings, convert them both to lowercase, explode each string on the space character into an array of strings and then loop through each looking for any word matches:
$var1 = preg_replace('/[.,]/', '', "Top of British");
$var2 = preg_replace('/[.,]/', '', "Welcome to British, the TOP country in the world");
$words1 = explode(" ",strtolower($var1));
$words2 = explode(" ",strtolower($var2));
foreach ($words1 as $word1) {
foreach ($words2 as $word2) {
if ($word1 == $word2) {
echo $word1."\n";
break;
}
}
}
DEMO: http://codepad.org/YtDlcQRA
Upvotes: 2
Reputation: 11467
PHP has a function for finding elements that are a member of two arrays:
$var1 = explode(" ", strtolower("Top of British"));
$var2 = explode(" ", strtolower("Welcome to British, the TOP country in the world"));
var_dump(array_intersect($var1, $var2)); // array(1) { [0]=> string(3) "top" }
Upvotes: 0
Reputation: 2972
Generic example for checking the intersection of words in phrases... you may check in the result for any obsolete stop-words like "of" or "to"
<?php
$var1 = "Top of British";
$var2 = "Welcome to British, the TOP country in the world";
$words1 = explode(' ', strtolower($var1));
$words2 = explode(' ', strtolower($var2));
$iWords = array_intersect($words1, $words2);
if(in_array('british', $iWords ) && in_array('top', $iWords))
echo "true";
Upvotes: 0
Reputation: 10685
To find TOP or BRITISH in the string
<?php
$var1 = "Top of British";
$var2 = "Welcome to British, the TOP country in the world";
$var1 = strtolower($var1);
$var2 = strtolower($var2);
if (strpos($var1, 'top') && strpos($var1, 'british')) {
echo "Either the word TOP or the word BRITISH was found in string 1";
}
?>
More generally match words in string 2 with those in string 1
<?php
$var1 = explode(' ', strtolower("Top of British"));
$var2 = "Welcome to British, the TOP country in the world";
$var2 = strtolower($var2);
foreach($var1 as $needle) if (strpos($var2, $needle)) echo "At least one word in str1 was found in str 2";
?>
Upvotes: 0