views:

44

answers:

4

Hi , I did a search but I didn't found anything . I'm looking for a pattern that will search in an alpha-numeric string (with the exact length of 7) the letter "P" . This is what I came up with until now , why isn't working ?

$pattern = "/^[\wP]{7}$/";

Many thanks in advance

A: 

Try this:

$pattern = '/^([a-zA-Z0-9]{6})(P{1})$/';

You could condider using strpos and strlen for speed!

PimPee
This pattern will only match a P at the end.
Bob Fincheimer
I changed it so it should be working correct now
PimPee
+1  A: 

Well it isn't working because [\wP]{7} (in your regex: /^[\wP]{7}$?/) means find 7 characters that are either a word character OR the letter P. It could find all Ps and it would match, or all word characters and it would match. My quick fix would be to verify the string is 7 letters long using a regex then do a string position to find the "P":

if(preg_match("/^[\w]{7}$/", $target) && strpos($target, "P") != -1) {
    // Do stuff
}
Bob Fincheimer
/^[\w]{7}$/ should be /^\w{7}$/D
stereofrog
A: 

\w contains a-z, A-Z, 0-9 and _ so it is not what you want at all.

I'll try with:

if ( preg_match("/^[a-z0-9]*P[a-z0-9]*$/i", $target) && ( strlen($target) == 7 ) ) { ... }
hsz
A: 

This should match any string that is 7 characters long and contains an uppercase P:

(?=^\w{7}$)\w*P\w*
Falle1234