0

I would like to know what is the best way to know if my substring is in the string.

So, I can has these kind of value :

"abcd.tif"
"abcd_A.tif"
"abcd_B.tif"
"abcd_VP.tif"

I would detect if "_A" or "_B" or "_VP" is present in the string.

What's the best way ? Using a combination of substr and strlen ?

or use regex ?

bahamut100
  • 1,795
  • 7
  • 27
  • 38
  • 6
    Ever seen the strpos() function (http://www.php.net/manual/en/function.strpos.php) in PHP? – Mark Baker Feb 07 '13 at 16:17
  • well, preg_match is moer efficient than strpos function, I guess (strpos will need three if/elseif block). So, I would encourage rather to use regular expression. – Rana Feb 07 '13 at 16:26
  • @MarkBaker > Indeed, not seen that, but I prefer to use preg_match – bahamut100 Feb 07 '13 at 16:28
  • @Rana I'd bet that three calls to `strpos` is still much faster than a single call to `preg_match`, so it is less *efficient*, but also more *readable* – Explosion Pills Feb 07 '13 at 16:40
  • @ExplosionPills, didn't know preg_match could be so slow, will look into. However, what about such more 10/20 checkings, which we can do in a single preg_match check instead of 10/20 if/else block? I will like to tell this a better implementation... – Rana Feb 07 '13 at 16:57
  • @Rana I have no idea at what point `preg_match` becomes more efficient to use, and it's probably not worth it in this case. String length matters to. This is not an exact check with respect to this problem, but it does show just how inefficient regular expressions can be: https://gist.github.com/ajcrites/4732454 – Explosion Pills Feb 07 '13 at 17:08

3 Answers3

6

Use strpos, which will give you the 0-indexed position of the needle in the string. If it's not in the string, strpos returns false. (There is also case-insensitive stripos).

However, you can only check one needle at a time. If you'd like to check for any of the three simultaneously you can either use a loop or write the terser but less efficient way:

preg_match('/_A|_B|_VP/', $str)

...which will return true if any of those three strings matches.

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
  • To find what matched, and where it was, you can use a capturing group and the `PREG_OFFSET_CAPTURE` flag. – nickb Feb 07 '13 at 16:22
0

The most efficient way (I know of :P) is strpos.

$s = 'abcd_VP.tif';
if (strpos('_A', $s) !== false) {
     // do your thing
}

You can do a simple || after this, it won't be as short, but it will be much quicker than regex:

$s = 'abcd_VP.tif';
if ((strpos('_A', $s) !== false) || (strpos('_B', $s) !== false) || (strpos('_VP') !== false)) {
     // do your thing
}
Vlad Preda
  • 9,780
  • 7
  • 36
  • 63
0

Use OR operation like (_A)|(_VP) etc. check this question as a hint: Regular Expressions: Is there an AND operator? , to use 'OR' in regular expression.

Community
  • 1
  • 1
Rana
  • 5,912
  • 12
  • 58
  • 91