matt
matt

Reputation: 44403

php test if string contains one of three strings?

What's the best way to achieve the following:

I have a $img variable containing e.g. myimage_left.jgp, someimage_center.jpg or img_right.jpg

What's the best way to test for _left, _right or _center of the filename and extract this value and store it in a variable?

So I have $img which already contains the complete basename of the file. And I need to have $pos which should hold _center or _left or _right.

What's the way to do that? preg_match, strpos, etc?

Upvotes: 3

Views: 4411

Answers (4)

Galen
Galen

Reputation: 30170

Non-regex option

$img = 'myimage_left.jpg';
$find = array( 'left', 'center', 'right' );

if ( in_array( $pos = end( explode( '_',  basename( $img, '.jpg' ) ) ), $find ) ) {
    echo $pos;
}

Upvotes: 1

Jon
Jon

Reputation: 437774

A regex would be simplest:

$input = 'foo_left.jpg';
if(!preg_match('/_(left|right|center)/', $input, $matches)) {
    // no match
}

$pos = $matches[0]; // "_left", "_right" or "_center"

See it in action.

Update:

For a more defensive-minded approach (if there might be multiple instances of "_left" and friends in the filename), you can consider adding to the regex.

This will match only if the l/r/c is followed by a dot:

preg_match('/(_(left|right|center))\./', $input, $matches);

This will match only if the l/r/c is followed by the last dot in the filename (which practically means that the base name ends with the l/r/c specification):

preg_match('/(_(left|right|center))\\.[^\\.]*$/', $input, $matches);

And so on.

If using these regexes, you will find the result in $matches[1] instead of $matches[0].

Upvotes: 12

Benjamin A
Benjamin A

Reputation: 53

Someone will probably have more elegant solution but I would use strpos like you suggest.

if (strpos(strtoupper($img), '_LEFT') > 0) $pos = '_LEFT'

you could then expand it to

$needleArray = arra('_LEFT', '_CENTER', '_RIGHT');
foreach ($needleArray as $needle) {
  if (strpos(strtoupper($img), $needle) > 0) $pos = $needle
}

This is assuming you can't have more than one value for pos.

Upvotes: 1

Doug T.
Doug T.

Reputation: 65639

If you want to avoid regexes, you could just do

  $underScores = explode("_", $img);
  $endOfFileName = end($underScores);
  $withoutExtensionArr = explode(".", $img);
  $leftRightOrCenter = $withoutExtensionArr[0];

Then check the contents of left right or center

Upvotes: 0

Related Questions