0

I'm trying to find a string inside a variable. The problem is that it doesn't look for a unique string.
For example, a have a variable with the following values:

$mystring = "p,pp,m,g";

Here's the code that I'm using:

<?php 
    $find="pp";
    if(strstr($mystring, $find)==true){
        echo "found"; 
    } 
?>

The problem is: when I'm looking for pp, it also returns "p" as a result. How can I avoid this kind of error?
I'm using it to check the sizes of a item on an ecommerce website and I'm struggling to get it right.

Any ideas?!

2
  • 1
    You don't need to check strstr($mystring, $find) == true. Commented Feb 6, 2013 at 12:40
  • I tried you code. It is working fine for me. It echo found if pp is found. If i remove pp from $mystring, it does not echo anything!!! Commented Feb 6, 2013 at 12:41

4 Answers 4

2

Use strpos. Make sure you use the !== operator.

echo strpos($mystring, $find) !== false ? 'found' : 'not found';
Sign up to request clarification or add additional context in comments.

2 Comments

@user1541940 then you need to use preg_match() and specify that you want no p next to it
right, it's harder than I thought...I'm thinking in just changing the sizes from letters to numbers...thanks anyway!
1
$mystring = "p,pp,m,g";
$str      = explode(",",$mystring);

$find     = "/^pp$/";
foreach($str as $val){
   if(preg_match($find, $val)){
       echo "found => ".$val; 
   }else{
       echo "not found";
   }
}

ref: http://php.net/manual/en/function.preg-match.php

4 Comments

Same problem here...it works but it returns true for p or pp because "pp" also has a "p"...got it?!
each , separated need to match ? OR it is a single string ?
each, separated need to match.
Edited the code please check it. Please note the ^ and $ in find string. ref: php.net/manual/en/function.preg-match.php
0

You can use transformating to array and search as array's element:

$mystring = "p,pp,m,g";
$arr = explode(',',$mystring);
if (in_array('p',$arr,true)) {echo "found";}

Or (http://php.net/manual/en/function.strstr.php: "If you only want to determine if a particular needle occurs within haystack, use the faster and less memory intensive function strpos() instead") you can write

if (strpos($mystring,'pp')!==false) {echo 'found';} else {echo 'not found';}

Comments

0

Just changed the values and used the same strstr function to avoid similar letters problem.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.