i have string like p88t9014-name
here is p
is for Product and t
for sub product id and after -
the name
is user defined any name. i try to match string with preg_match
with this code ::
$name="p88t0056-name";
if(preg_match('/p[0-9]t[0-9]-[A-Z,a-z]/',$name,$match)) {
echo "yes";
} else {
echo "No";
}
print_r($m);
i just try to match formate if is this with format p[number]t[number]-[anystring]
. but my code is not working.
您需要在字符类之后放置量词:
'/p[0-9]+t[0-9]+-[A-Za-z]+/'
This regex will work for you:
/p(\\d+)t(\\d+)-(\\w+)/g
Explaination:
p
matches letter p
\\d+
matches numbers 0-9
t
matches letter t
\\d+
matches numbers 0-9
-
matches dash '-'
\\W+
match any word character [a-zA-Z0-9_] and g to catch all matches.
I am also not an expert on regex but trying multiple options on http://www.regex101.com helps as it shows explanations of characters in right side panel. Hope it helps in future :)
If you're always going to have a set number of digits, you can also use:
/^p[0-9]{2}t[0-9]{4}-[A-Za-z]+$/
Here's an example on RegExr: http://www.regexr.com/390ds
in regex [0-9]
matches exactly one character, and so does [AZ,az]
, and therefore $name is not match the pattern you give. Strings like "p8t0-A" and "p0t2," pass the test.
Besides, another problem in your pattern is that: [AZ,az]
matches not only alphabets but also ,
(a single comma). I guess the pattern you need is p[0-9]+t[0-9]+-[A-Za-z]+
, in which +
s represent "occurs at least once".
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.