开发者

PHP regexp for checking letters except W, w, P, p

I need a regexp pattern, that checks if string contains letters excepting W, w, P, p.

$pattern = ''; // I need this pattern
preg_match($pattern, '123123'); // false
preg_match($pattern, '123123a'); // true
preg_match($pattern, '123123W'); // false
开发者_高级运维preg_match($pattern, '123123w'); // false
preg_match($pattern, '123123P'); // false
preg_match($pattern, '123123p'); // false
preg_match($pattern, '123123WwPp'); // false
preg_match($pattern, 'abcWwPp'); // true
preg_match($pattern, 'abc'); // true

Thank you in advance.


If you only care for ASCII letters, check for

[^\W\d_WP]

and make the search case-insensitive:

preg_match('/[^\W\d_WP]/i', $subject)

[^\W\d_WP] matches a character that is alphanumeric, substracting digits, underscore, W and P from the list of allowed characters. [^\W] looks counterintuitive since it means "not a non-alphanumeric character", but that double negative pays off because I can then substract other characters from the result.

If you care about Unicode letters, use

preg_match('/[^\PLWP]/iu', $subject)

\PL matches any character that is not a Unicode letter (opposite of \pL)


Search for the range outside of w and p - like this

/[a-oq-vx-z]/i

Note the i at the end for case insensitive


This is not an answer but a little program to check Tim Pietzcker expression: it works according to the test provided by Billy.

<?php

error_reporting(E_ALL);
$pattern = '/[^\W\d_WP]/i'; 

assert(!preg_match($pattern, '123123'));
assert(preg_match($pattern, '123123a'));
assert(!preg_match($pattern, '123123W'));
assert(!preg_match($pattern, '123123w'));
assert(!preg_match($pattern, '123123P'));
assert(!preg_match($pattern, '123123p'));
assert(!preg_match($pattern, '123123WwPp'));
assert(preg_match($pattern, 'abcWwPp')); 
assert(preg_match($pattern, 'abc'));

?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜