Dragon54
Dragon54

Reputation: 313

Check for dot in string name

I'm looking for a way so my php script can give a true or false when the string it searches in contains some characters after a dot in that exact order.

For example:

My string is: .htpassword

My script may only give true when it finds the string in my array containing a dot followed by some alphabetical characters and only in that order.

I've looked into the strpos() function but that doesn't fit my needs as I have some files containing characters with a dot after the characters.

Valid match:

Invalid matches:

My script so far I've written:

$arr_strings = $this->list_strings();

            $reg_expr_dot = '/\./';
            $match = array();

            foreach ($arr_strings as $string) {
                if (preg_match_all($reg_expr_dot, $file, $match) !== FALSE) {
                    echo "all strings: </br>";
                    echo $match[1] . "</br></br>";

                }
            }

Thanks in advance for any help!

Kind regards

Upvotes: 2

Views: 2132

Answers (3)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89574

Try this: (if I have well understand)

$arr_strings = $this->list_strings();

$reg_expr_dot = '/^\.[a-z]+$/i';

$intro = 'all strings: <br/>';
foreach ($arr_strings as $string) {
    if (preg_match($reg_expr_dot, $string, $match)) {
        echo $intro . $match[0];
        $intro = '<br/>';
    }
}

to be sure that an entire string is exactly as in your most crazy dreams, you can use anchors (at the begining ^ and at the end $) otherwhise your pattern could match a substring and return true. (You avoid to match zzzz.htaccess and .htaccess#^..+=)

The character class [a-z] contains uppercase letters too since I use the i modifier (case insensitive) at the end of the pattern.

Upvotes: 3

Hugo Firth
Hugo Firth

Reputation: 535

I'm not sure if I fully understand the question but something like /^\\.[a-zA-Z]+$/u should suit your needs.

    $strings = $this->list_strings();
    $matches = array();

    foreach($strings as $string){
        if(preg_match("/^\\.[a-zA-Z]+$/u", $string)){
            $matches[] = $string;
        }
    }

    echo "all strings: </br>";

    foreach($matches as $match){
        echo $match."</br>"; 
    }

Let me know how it goes.

Upvotes: 1

jlewkovich
jlewkovich

Reputation: 2775

Try this /^\.[a-zA-Z]+/ - If there are additional criteria, let me know. I assumed '.' followed by any lowercase/uppercase character

Upvotes: 1

Related Questions