Comparing Strings

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
theoph
Forum Commoner
Posts: 47
Joined: Wed Jul 30, 2003 5:26 pm
Location: Lexington, KY USA

Comparing Strings

Post by theoph »

I know this may seem like a newbie question, but I have a problem that I need help on.

I'm wanting to compare two strings.

String1 = apples
String2 = apples, oranges

I want to test and make sure that apples is in contained in both strings. What is the best function to use?

-Newbie Dave
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

really depends on what you're trying to achieve.
Might be string strstr ( string haystack, string needle) is sufficient
theoph
Forum Commoner
Posts: 47
Joined: Wed Jul 30, 2003 5:26 pm
Location: Lexington, KY USA

Post by theoph »

Sometime like this . . .

if (Var1) [is in] (Var2)
{
do this;
}
else
{
do that;
{
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

then http://php.net/strstr is what you're looking for

Code: Select all

<?php
$Var1 = 'apples';
$Var2 = 'apples, oranges';
if (strstr($Var2, $Var1)!==FALSE)
{
 	echo 'do this';
}
else
{
	echo 'do that';
}
?>
or http://php.net/strpos which might be slightly faster

Code: Select all

<?php
$Var1 = 'apples';
$Var2 = 'apples, oranges';
if (strpos($Var2, $Var1)!==FALSE)
{
 	echo 'do this';
}
else
{
	echo 'do that';
}
?>
m3rajk
DevNet Resident
Posts: 1191
Joined: Mon Jun 02, 2003 3:37 pm

Post by m3rajk »

depends, foir checking that one is part of 2, use what they suggest.
for checking that a certain string is in a set of strings, then you're doing pattern matching.


preg_match('/string/i', $strings);
User avatar
JAM
DevNet Resident
Posts: 2101
Joined: Fri Aug 08, 2003 6:53 pm
Location: Sweden
Contact:

Post by JAM »

exactly what ststr/strpos is doing.
It is also faster than preg.
theoph
Forum Commoner
Posts: 47
Joined: Wed Jul 30, 2003 5:26 pm
Location: Lexington, KY USA

Post by theoph »

YAHOO it worked perfectedly!!

With everyone's help with this bit of code, I now am able to write a PHP code that is able to multiple select items in a form's menu box from a MySQL database.

Code: Select all

<?php 
			do {
				if(strpos($row_rsLaos['s_cell'],$row_rsCellmenu['name'])!==FALSE)
				{
					$check = 'SELECTED';
				}
				else
				{
					$check = '';
				}
				echo '<option value="'.$row_rsCellmenu['name'].'" '.$check.'>'.$row_rsCellmenu['name'].'</option>';
			}
			while ($row_rsCellmenu = mysql_fetch_assoc($rsCellmenu));
?>
Post Reply