How to find all the file names that contain hello, English and end with .apk.
I currently have a regular expression that I use to find file names that contain hello and end with .apk.
preg_match('/.*hello.*\.apk$/i', $filename);
You could do that with regular expressions but you'll eventually end up with ugly/complex/illegible expression. Instead use conjunction of simplier conditions joined togheter with logic operators:
if (strpos($filename, 'hello') !== 0 && strpos($filename, 'English') !== 0 && substr($filename, -4) === '.apk') {
// filename matches
}
PHP's lack of standard string functions like contains() or starts|endsWith() makes above code a little bit ugly, but there's nothing that stopes you from creating a helper, utility class:
class StringHelper {
private $subject;
public function __construct($subject) {
$this->subject = $subject;
}
public function contains($substring) {
return strpos($this->subject, $substring) !== false;
}
public function endsWith($string) {
return substr($this->subject, strlen($string) * -1) === $string;
}
}
Then your if becomes even simpler:
$filename = new StringHelper($filename);
if ($filename->contains('hello') && $filename->contains('English') && $filename->endsWith('.apk')) {
// matches
}
Hint: Instead of creating StringHelper object you could use a "classical" StringUtilis class with a bunch of static methods that accepts $string as their first argument.
Hint: StringHelper::contains() could accept an array of strings and check whether your string contains them all or at least one of them (depending on some sort of a flag given in second argument).
This regex should do the trick if you need 'hello' OR 'English' in the file name :
/.*(hello|English).*\.apk$/
hello and EnglishIf "English" must come after "hello":
if(preg_match('/.*hello.*English.*\.apk$/i', $filename));
If they can be in any order:
if(preg_match('/(hello.*English|English.*hello).*\.apk$/i', $filename));
'/(hello.*English|English.*hello).*\.apk$/i' should work, even if there's probably a more elegant way..