$a = \'how are you\';
if (strpos($a,\'are\') !== false) {
echo \'true\';
}
In PHP, we can use the code above to check if a string contain speci
indexOf
/includes
should not be used for finding whole words:It does not know the difference between find a word or just a part of a word:
"has a word".indexOf('wor') // 6
"has a word".includes('wor') // true
Find a real whole word, not just if the letters of that word are somewhere in the string.
const wordInString = (s, word) => new RegExp('\\b' + word + '\\b', 'i').test(s);
// tests
[
'', // true
' ', // true
'did', // true
'id', // flase
'yo ', // flase
'you', // true
'you not' // true
].forEach(q => console.log(
wordInString('dID You, or did you NOt, gEt WHy?', q)
))
console.log(
wordInString('did you, or did you not, get why?', 'you') // true
)
var stringHasAll = (s, query) =>
// convert the query to array of "words" & checks EVERY item is contained in the string
query.split(' ').every(q => new RegExp('\\b' + q + '\\b', 'i').test(s));
// tests
[
'', // true
' ', // true
'aa', // true
'aa ', // true
' aa', // true
'd b', // false
'aaa', // false
'a b', // false
'a a a a a ', // false
].forEach(q => console.log(
stringHasAll('aA bB cC dD', q)
))