Jump to content

why isn't my strpos working.


iPixel

Recommended Posts

I've got a field, it get's passed to this php page.

 

That field passes data that looks like so:  

MC#1. This is some regular text, no big deal.

 

MA#2. Some more text, again no big deal

 

Here's my script:

<?php

$test_data = explode("\n\n", $test_data);

foreach($test_data as $text=> $value)
{
	if(strpos($value,'MC#'))
		{
			echo $value;
                                //Note: $values echoed value = "MC#1. This is some regular test, no big deal."
		}
	else
		{
			echo "<br />Did not find MC#<br />";	
		}
}

?>

 

 

My Issue, is that the "IF" always fails. Clearly $value has MC# in the string but still doesn't find it.

I've also tried if(strpos($value,'MC#') === true) and other variations of the two. But no luck, for each $test_data it never finds MC#.

 

I'm sure i'm missing something. However, i have no clue what.

 

Thanks!

 

Link to comment
https://forums.phpfreaks.com/topic/267383-why-isnt-my-strpos-working/
Share on other sites

The problem is that strpos() is returning 0 (because that is the position of the match), which PHP is interpreting as "false" (because PHP is a loosely-typed language).

 

You tried if (strpos() === true), but that won't work because strpos() never returns boolean true. It only returns the position (if found) or boolean false (if not found).

 

So, the solution is thus: if (strpos($value, 'MC#') === 0) {

 

EDIT: Actually, if you want to check if "MC#" exists anywhere in the string, you can go with: if (strpos($value, 'MC#') !== false) {

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.