如何在PHP中设置正则表达式

时间:2013-06-14 22:29:07

标签: php preg-match

我想知道如何获得以下文本的正则表达式:

XXXXXX[Some Same Text # AAAA-NNNN]XXXXXX

其中:

'X' can vary any text: Alfa, numerical or symbols (The X can have 0 to infinite characters and it is NOT obligatory).
'A' Alfa uppercase text (The Alfa has exactly 4 uppercase letters and it is obligatory).
'N' Numbers (The N have exactly 4 numbers and it is obligatory).
'Some Same text' has exactly the same text always and it is obligatory.
'[,],#,-' will always be there in that same possition and it is obligatory.

我有一个preg_match:

*[Some Same Text([A-Z]{4})-([0-9]{4})]*

它似乎没有起作用。

谢谢和问候!

2 个答案:

答案 0 :(得分:2)

.匹配任何字符,*表示0..infinity。 使用[]时,您需要逃避它们。试试这个:

.*\[Some Same Text # ([A-Z]{4})-([0-9]{4})\].*

答案 1 :(得分:1)

这应该有效:'/^.*\[Some Same Text\s#\s[A-Z]{4}-\d{4}\].*$/'。经过测试:

if(preg_match('/^.*\[Some Same Text\s#\s[A-Z]{4}-\d{4}\].*$/', 'XXXXXX[Some Same Text # AAAA-4444]XXXXXX'))echo 1;