Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Word contained in string

Status
Not open for further replies.

Steve-vfp9user

Programmer
Feb 5, 2013
335
GB
Hello
I am new to php and trying find out how I can create an If/Then statement when a known word is encountered and contained in the string. Research has found these but these are = to:

Code:
True statement

$number_three = 3;

if ( $number_three == 3 ) {
	echo "The if statement evaluated to true";
} else {
	echo "The if statement evaluated to false";
}


False statement

$number_three = 421;

if ( $number_three == 3 ) {
	echo "The if statement evaluated to true";
} else {
	echo "The if statement evaluated to false";
}



Thank you

Steve
 
A string variable comprising of numerals must be enclosed in quote marks to be a 'string' otherwise it will take a numeric value. So testing 3 against 421 WILL be false just as testing 3 against 321 would be false because 3 != 421 || 321

To find a character or word in a string you should use strpos (position in string) or strrpos (reverse position in string)






Chris.

Indifference will be the downfall of mankind, but who cares?
Time flies like an arrow, however, fruit flies like a banana.
Webmaster Forum
 
Hi Chris
Thank you for the response.
Problem I have is that I may not always know where the word may be in the actual string. I use Visual Foxpro and issue:

myvar="somename"
IF myvar $ MYFIELD
* True if found...
ENDIF

I know it's not the same in php but that might better explain my goal.

Thank you

Steve
 
strpos FINDS the word in the string you don't need to know it is there or where it is

It's the PHP equivalent of instr() and if it doesn't find it in the string it returns "false", if it does match it, the return value is an integer.

Chris.

Indifference will be the downfall of mankind, but who cares?
Time flies like an arrow, however, fruit flies like a banana.
Webmaster Forum
 
Code:
$string = "the quick brown fox jumps over the lazy black dog";
$search = "jumps";
$result = strpos($string,$search);
if($result === false): //nb must test for === or !==
 echo 'no match';
else:
 echo 'match';
endif;

alternative approaches include regex, lexing and array transformations. strpos is the most efficient in this case, but for true word boundary matching you will probably want one of the first two. eg.

Code:
$result = preg_match("|\b$search\b|", $string);
 
And, .... if you want a case insensitive seek use stripos()

Chris.

Indifference will be the downfall of mankind, but who cares?
Time flies like an arrow, however, fruit flies like a banana.
Webmaster Forum
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top