Page 1 of 1

Help With Strings

Posted: Sun Oct 05, 2008 2:06 am
by profitweaver
Hi,

I am a novice at this.

I am trying to find an instance of a string within another string. I have found several functions that do this. I have tested the functions and they seem to work ok, so I know the syntax is correct.

However, I am passing a variable containing one string to this function in another file. The string is being passed ok, but the function will not correctly tell me that one string contains another when I know that it does.

For example.

<?php
$pos = stristr("<?=$cat?>", "<?=$choosecat?>");
if ($pos === false)
echo "The string '$choosecat' was not found in the string '$cat'";
else {
echo "The string '$choosecat' was found in the string '$cat'";
echo " and exists at position $pos";
}
?>

always returns false.

Can anyone give me a clue why this isn't working please?

Thanks

Re: Help With Strings

Posted: Sun Oct 05, 2008 2:50 am
by josh
Well first of all strpos() is the string function that returns string position, second of all have you checked that the variable does contain the said string but, hmm lets say... ( and this might be a totally crazy idea ) but outputting the variable before you call the function to see if it contains the string?

I would expect it to return false for those hard coded values, since neither one of those strings contains the other.

Re: Help With Strings

Posted: Sun Oct 05, 2008 4:01 pm
by califdon
profitweaver wrote:$pos = stristr("<?=$cat?>", "<?=$choosecat?>");
Try:

Code: Select all

$pos = stristr(" . <?php echo $cat; ?> . ", " . <?php echo $choosecat; ?> . ");

Re: Help With Strings

Posted: Sun Oct 05, 2008 5:41 pm
by josh
califdon wrote:
profitweaver wrote:$pos = stristr("<?=$cat?>", "<?=$choosecat?>");
Try:

Code: Select all

$pos = stristr(" . <?php echo $cat; ?> . ", " . <?php echo $choosecat; ?> . ");
I'm sorry I don't see the logic, the haystack does not contain the needle

Re: Help With Strings

Posted: Sun Oct 05, 2008 6:10 pm
by califdon
To be sure. My bad.

Code: Select all

<?php
 
$pos = stristr("$cat", "$choosecat"); 
 
?>
Even this contains assumptions about the values of those variables, but should give the OP some idea of how to use string search. I hope.

Re: Help With Strings

Posted: Sun Oct 05, 2008 6:43 pm
by josh
hmm, forget about variable expanding also, I thought those were single quotes.. my bad as well, yes you would need to double check the value of those variables as well, unless you're trying to use the variable names literally..

Anyways you still want strpos()

Re: Help With Strings

Posted: Mon Oct 06, 2008 4:09 am
by profitweaver
Thanks for your efforts people.

I have discovered that

$pos = stristr($cat,$choosecat);

Does what I need. I was over complicating matters.