views:

199

answers:

3

I am using strpos() to find the needle in the haystack. But, I want it to only find the needle with the same string length. E.g.:

$mystring = '123/abc';
$findme   = 'abc';
$pos = strpos($mystring, $findme); // THIS IS FINE

$mystring = '123/abcdefghijk';
$findme   = 'abc';
$pos = strpos($mystring, $findme); // THIS IS NOT FINE

So, I need to check the string length of the found string and match that to the needle to see if they are the same length. So, 123/abc matches abc correctly, but I don't want 123/abcdefghijk to match abc because it is much longer than 3 characters.

+1  A: 

substr() can take a negative3 argument which counts from the end of the string. So figure out the length of the needle, count off that many characters from the end and compare it to the needle:

if (substr($mystring, -strlen($findme)) == $findme) {
  ...
}
cletus
+1  A: 

The question is pretty vague ('123/abc' is clearly longer than 3 characters as well!), but you might be looking for substr_compare() with a negative index.

TML
A: 

Are you saying the slashes are significant, ie. you only want to match the needle when it is one in a series of slash-separated tokens?

If so, you could either try regex:

preg_match('/(^|\/)abc($|\/)/', $mystring, $matches, PREG_OFFSET_CAPTURE);
$pos= FALSE;
if (count($matches)>=1)
    $pos= $matches[0][1];

Or split on the slashes and work with separate string parts:

$parts= explode('/', $mystring);
$pos= array_search($parts, 'abc');
if ($pos!==FALSE)
    $pos= count(implode('/', array_slice($parts, 0, $pos)));

Regex is probably a little faster. But the latter would be a better move if you need to match arbitrary slash-separated strings that might contain regex-special characters.

bobince