Jump to content

[SOLVED] Checking if 2 words are in a text


Nexy

Recommended Posts

Why Hello There!  :) How would I be able to something like this:

 

if($text contains a specific word == "word1" && $text contains another specific word == "word2")

{

        do something;

}

 

Basically, if word1 and word2 are in the variable $text in respective order, then do something. Also, $text can contain any other words in there too. So if there was something like this:

 

$text = "Hello word1 there! Welcome to word2 today!";

 

Then the if statement would see those 2 words are in there in order. But if it's something like this:

 

$text = "Hello word2 there! Welcome to word1 today!";

 

Then do nothing, since "word1" is not first. I hope that made sense. Any help would be appreciated.

 

Thank You!  :)

Link to comment
Share on other sites

try this

if(!strstr(strstr($text,"word1"),"word2")===false){

strstr will return the part of the string after it finds the first occurrence so you search for word1 in

Hello word1 there! Welcome to word2 today

you get

 there! Welcome to word2 today

so then you search again for word to and if it cant find it it will return FALSE

 

Scott.

Link to comment
Share on other sites

or you may also try:

 

<?php
if(strpos(strstr($mystring, $word1), $word2) !== false) {
	echo "Match found";
}
?>

 

the reason i replaced the strstr() in the last one with strpos() is because we only aim to get the occurence other than the string itself since strpos() is faster and less memory intensive function.

 

if you want to totally remove strstr(), you may use strpos() then just apply the third parameter offset which is the result of the first strpos() + strlen() of the first string... which i think may only become more costly, though I haven't used this one and untested. :)

 

EDIT:

 

oh, somebody made a post already... ahahah :D

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.