I have a large string chunk of text, and I need to extract all occurrences of text matching the following pattern:
QXXXXX-X
(where X can be any digit, 0-9).
How do I do this in PHP?
<?php
preg_match_all("","Q05546-8 XXX Q13323-0",$output,PREG_PATTERN_ORDER);
print_r($output);
?>
Here you go:
preg_match_all('/\bQ[0-9]{5}-[0-9]\b/',"Q05546-8 XXX Q13323-0",$output,PREG_PATTERN_ORDER);
print_r($output);
Or, you can use shorthand class \\d
for a digit: \\bQ\\d{5}-\\d\\b
.
Regex explanation :
\\b
- Word boundary (we are either at the beginning of between a word character ( [a-zA-Z0-9_]
) and a non-word one (all others) Q
- Literal case-sensitive Q
[0-9]{5}
- Exactly 5 (due to {5}
) digits from 0
to 5
range -
- Literal hyphen [0-9]
- Exactly 1 digit from 0
to 5
\\b
- Again a word boundary. If you have these values inside longer sequences, you may consider using \\bQ[0-9]{5}-[0-9](?![0-9])
or using shorthand classes, \\bQ\\d{5}-\\d(?!\\d)
.
Output of the demo :
Array
(
[0] => Array
(
[0] => Q05546-8
[1] => Q13323-0
)
)
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.