1

How do I find exact 2, in a string using strpos? Is it possible using strpos? The example below returns "Found" even though the match is NOT exact to what I need. I understand 2, is matching with 22,. It should return "Not Found". I am matching ID's in this example.

$string = "21,22,23,26,";
$find = "2,";

$pos = strpos($string, $find);
if ($pos !== false) {
   echo "Found";
} else {
   echo "Not Found";
}

3 Answers 3

4

Unless the string is enormous, make an array and search it:

$string = "21,22,23,26,";
$arr = explode(",", $string);

// array_search() returns its position in the array
echo array_search("2", $arr);
// null output, 2 wasn't found

Actually, in_array() is probably faster:

// in_array() returns a boolean indicating whether it is found or not
var_dump(in_array("2", $arr));
// bool(false), 2 wasn't found 
var_dump(in_array("22", $arr));
// bool(true), 22 was found

This will work as long as your string is a comma-delimited list of values. If the string is really long, making an array may be wasteful of memory. Use a string manipulation solution instead.

Addendum

You didn't specify, but if by some chance these strings came from a database table, I would just add that the appropriate course of action would be to properly normalize it into another table with one row per id rather than store them as a delimited string.

Sign up to request clarification or add additional context in comments.

1 Comment

I don't see this comma seperated string being longer than 20-30 at most. So I didn't make it it's own DB table
1

Try with explode and in_array

Example:

$string = "21,22,23,26,";
$string_numbers = explode(",", $string);
$find = 2;
if (in_array($find, $string_numbers)) {
   echo "Found";
} else {
   echo "Not Found";
}

Comments

1

You can use preg_match if you want to avoid arrays.

    $string = "21,22,23,26,";
    $find = '2';
    $pattern = "/(^$find,|,$find,|,$find$)/";
    if (0 === preg_match($pattern, $string)) {
        echo "Not Found";
    } else {
        echo "Found";
    }

This will find your id at beginning, middle or at the end of the string. Of course, I am assuming $string does not contain characters other than numbers and commas (like spaces).

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.