Php test if line contains one of three lines?

What is the best way to achieve the following:

I have a $img variable containing, for example, myimage_left.jgp , someimage_center.jpg or img_right.jpg

What is the best way to check for _left , _right or _center the file name and extract this value and save it in a variable?

So, I have $img , which already contains the full base file name. And I need to have $pos , which should contain _center or _left or _right .

How to do it? preg_match, strpos, etc.

+2
source share
4 answers

The mode will be easier:

 $input = 'foo_left.jpg'; if(!preg_match('/_(left|right|center)/', $input, $matches)) { // no match } $pos = $matches[0]; // "_left", "_right" or "_center" 

Look in action .

Update:

For a more secure approach (if there can be multiple instances of "_left" and friends in the file name), you might consider adding to the regular expression.

This will only match if a dot follows l / r / c:

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

This will only match if l / r / c is followed by the last dot in the file name (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 you use these regular expressions, you will find the result in $matches[1] instead of $matches[0] .

+12
source

Someone will probably have a more elegant solution, but I would use strpos as you suggest.

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

you can expand it to

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

It is assumed that for pos there cannot be more than one value.

+1
source

Parameter without regular expression

 $img = 'myimage_left.jpg'; $find = array( 'left', 'center', 'right' ); if ( in_array( $pos = end( explode( '_', basename( $img, '.jpg' ) ) ), $find ) ) { echo $pos; } 
+1
source

If you want to avoid regular expressions, you can just do

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

Then check the contents left or right

0
source

All Articles