Page 1 of 1

Comparing Strings

Posted: Thu Oct 02, 2003 6:12 pm
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

Posted: Thu Oct 02, 2003 9:05 pm
by volka
really depends on what you're trying to achieve.
Might be string strstr ( string haystack, string needle) is sufficient

Posted: Thu Oct 02, 2003 10:57 pm
by theoph
Sometime like this . . .

if (Var1) [is in] (Var2)
{
do this;
}
else
{
do that;
{

Posted: Thu Oct 02, 2003 11:39 pm
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';
}
?>

Posted: Fri Oct 03, 2003 1:29 am
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);

Posted: Fri Oct 03, 2003 4:14 am
by JAM
exactly what ststr/strpos is doing.
It is also faster than preg.

Posted: Fri Oct 03, 2003 9:25 am
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));
?>