Home > front end >  Regex pattern for getting the the string value from the filename
Regex pattern for getting the the string value from the filename

Time:07-06

I'm stuck on getting the value with an underscore separator. I used preg_match(PHP) but didn't get the correct regex pattern. This is the sample pattern of the filename.

xxxx_get-thisValue_more details_20200728173715594600.zip get-thisValue_more details_20200728173715594600.zip getThisValue_20200728173715594600.zip

All I want is to get the get-thisValue or getThisValue string on the filename pattern, thanks in advance btw here is my code

<?php 
$filename = 'xxxx_get-thisValue_more details_20200728173715594600.zip';
preg_match('/(.*_)?(.*)_[0-9] .zip/', $filename, $matches);
echo $prefix = $matches[2];

?>

CodePudding user response:

You could use for example a capture group:

([^_\s] )(?:_[^\n_-] )?_\d \.zip$

Explanation

  • ([^_\s] ) Capture group 1, match any char except _ (or a whitespace)
  • (?:_[^\n_-] )? Optionally match _ and then any char except _ or -
  • _\d \.zip Match _ 1 digits and .zip
  • $ End of string

Regex demo

Example

$re = '/([^_\s] )(?:_[^\n_-] )?_\d \.zip$/m';
$str = 'xxxx_get-thisValue_more details_20200728173715594600.zip
get-thisValue_more details_20200728173715594600.zip
getThisValue_20200728173715594600.zip
xxxx_get-thisValue_more details_20200728173715594600.zip
xxxx_getthisValue_more details_20200728173715594600.zip
1111_get-thisValue_more details_20200728173715594600.zip
1111_getthisValue_more details_20200728173715594600.zip
get-thisValue_more details_20200728173715594600.zip
getthisValue_more details_20200728173715594600.zip
get-thisValue_20200728173715594600.zip
getthisValue_20200728173715594600.zip';

preg_match_all($re, $str, $matches);

print_r($matches[1]);

Output

Array
(
    [0] => get-thisValue
    [1] => get-thisValue
    [2] => getThisValue
    [3] => get-thisValue
    [4] => getthisValue
    [5] => get-thisValue
    [6] => getthisValue
    [7] => get-thisValue
    [8] => getthisValue
    [9] => get-thisValue
    [10] => getthisValue
)

See a PHP demo.

  • Related