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!  :)

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.

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.