0

for example, i have these few keywords

$word = "word1,word2,word3";

and substract/explode that using $keyword = explode(",", trim($word)); then ill get these $keyword[0] $keyword[1] and $keyword[2]

now, how to match these keyword using preg_match?

$others = "this is example where there is word1"; 

if(preg_match('/($keyword[0]|$keyword[1]|$keyword[2])/i', $others)){
echo "matched";
}

the problem is, if there is only 2 words, it will matched all the words in $others.

is there any more propper or easier and efficient way to do it?

1
  • 2
    Do you need to initialize the regex from an array? Try $rx = '/' . implode("|", array_map(function($i) { return preg_quote(trim($i), "/"); }, explode(",", $word))) . '/i';, then use preg_match($rx, $others), see demo. Add word boundaries, \b, on both ends to only match whole words. Or, better, (?<!\w) at the start and (?!\w) at the end. Commented Mar 28, 2020 at 9:59

1 Answer 1

1

Use array_intersect() along with explode()

$word = "word1,word2,word3";

$others = "this is example where there is word1"; 


$wordsArray = explode(',',$word);
$othersArray = explode(' ',$others);
if(count(array_intersect($othersArray,$wordsArray)) > 0){
    echo "matched";
}else{
    echo "not matched";
}

Output: https://3v4l.org/2fiTm And https://3v4l.org/vIrnh

if you want case insensitive check then use strtolower():

$wordsArray = explode(',',strtolower($word));
$othersArray = explode(' ',strtolower($others));
if(count(array_intersect($othersArray,$wordsArray)) > 0){

    echo "matched";
}else{
    echo "not matched";
}

Output: https://3v4l.org/tgflb

Note:- I assume that text($others variable) words are separated with white space.

Sign up to request clarification or add additional context in comments.

2 Comments

so the $othersArray explode every words? does it takes a long time if the $others has a long sentence? i mean if the $others is long, does is it affect the server?
nope. it needs to be too-too-too-too-too........... long to affect server speed. you can check it here:- 3v4l.org/t4XUG/perf#output

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.