echo preg_match('/\d/','h0w many d1g1t5 ar3 th3r3');
This example will output 7. Nice and simple really; if there had been no numbers in
the subject then it would have outputted 0.
Let's take another approach to preg_match(); we can return occurrences of blocks
from a pattern. We define blocks by encapsulating them in parentheses. A good
example of this is parsing a date.
$matches = array();
$pattern = '/^(\d{4})\D(\d{1,2})\D(\d{1,2})$/';
$value = '1791-12-26';
preg_match($pattern, $value, $matches);
print_r($matches);
Before you run away screaming, let's break this down into its component parts.
The pattern says: start of string, 4 digits, 1 non-digit, 1 or 2 digits, 1 non-digit, 1 or 2
digits, end of string. It's not all that complex, it just looks it. This will output:
Array
(
[0] => 1791-12-26
[1] => 1791
[2] => 12
[3] => 26
)
The first element of the array is the text that matched the full pattern. The rest of the
elements are the matching blocks.
Chapter 11
[ 323 ]
Replacing
We can use preg_replace() to replace patterns with alternative text.
Pages:
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444