bahamut100
bahamut100

Reputation: 1837

How to find an occurence in string?

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 ?

Upvotes: 0

Views: 99

Answers (3)

Rana
Rana

Reputation: 6154

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.

Upvotes: 0

Vlad Preda
Vlad Preda

Reputation: 9910

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
}

Upvotes: 0

Explosion Pills
Explosion Pills

Reputation: 191749

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.

Upvotes: 6

Related Questions