Reputation: 42139
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.
Upvotes: 0
Views: 793
Reputation: 536369
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.
Upvotes: 0
Reputation: 12966
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.
Upvotes: 1