Richard Allsopp
Richard Allsopp

Reputation: 37

regular expression to match two different strings in PHP

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);

Upvotes: 0

Views: 297

Answers (3)

ithcy
ithcy

Reputation: 5589

If "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));

Upvotes: 1

Crozin
Crozin

Reputation: 44376

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).

Upvotes: 3

magnetik
magnetik

Reputation: 4431

This regex should do the trick if you need 'hello' OR 'English' in the file name :

/.*(hello|English).*\.apk$/

Upvotes: 1

Related Questions