0

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}$/";
2
  • Can you give some positive and negative hits? Commented Aug 9, 2010 at 11:09
  • Thanks guys , I eventually switched to strlen and strpos Commented Aug 9, 2010 at 23:24

4 Answers 4

1

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
}
Sign up to request clarification or add additional context in comments.

Comments

0

Try this:

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

You could condider using strpos and strlen for speed!

1 Comment

This pattern will only match a P at the end.
0

\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 ) ) { ... }

Comments

0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.