Venkatraman
Venkatraman

Reputation: 3

Search for a text starting with a character and of specific length

$sourceArray = array('venkat', 'bala', 'vignesh', 'vardan', 'harishv');

output must be an array which has values starting with 'v' and of length 6 chars.

Following must be the output array for the above sourceArray as input

$outputArray = ('venkat','vardan');

I tried preg_grep('/^([v.]{6,6})/',$sourceArray)); which returned my an empty array.

Can anyone tell me where I went wrong?

Upvotes: 0

Views: 62

Answers (4)

Ovidiu B
Ovidiu B

Reputation: 106

You can have the regex doing it or you can do the following:

$results = array();
$startLetter = "v";

foreach($sourceArray as $key){
    if($key[0] == $startLetter && strlen($key) == 6 )
    {
        $results[] = $key;
    }
}

I hope it helps!

Upvotes: 0

DaveyBoy
DaveyBoy

Reputation: 2924

Try preg_grep('/^(v.{5})$/',$sourceArray); (I've not checked this so may be wrong)

The '.' in the [...] structure is actually matching the period rather than any character

Upvotes: 0

Robin
Robin

Reputation: 9644

Your regex matches "a v or a dot . 6 times". You can use instead:

^v.{5}$

A v, followed by 5 characters.

Upvotes: 2

blue
blue

Reputation: 1949

The regular expression to use is:

/^v.{5}$/

Here is the code that produces what you've expect:

$sourceArray = array('venkat', 'bala', 'vignesh', 'vardan', 'harishv');

var_dump(
    preg_grep('/^v.{5}$/',$sourceArray)

Upvotes: 3

Related Questions