Regular Expressions in PHP

Here’s the translation of the Go code for regular expressions to PHP, along with explanations in Markdown format suitable for Hugo:

Our example demonstrates common regular expression tasks in PHP. PHP offers built-in support for regular expressions through the PCRE (Perl Compatible Regular Expressions) library.

<?php

// This tests whether a pattern matches a string.
$match = preg_match('/p([a-z]+)ch/', 'peach', $matches);
echo $match ? "true\n" : "false\n";

// In PHP, we don't need to compile the regular expression separately.
// We can use it directly in the preg_* functions.

// This finds the match for the regexp.
preg_match('/p([a-z]+)ch/', 'peach punch', $matches);
echo $matches[0] . "\n";

// This also finds the first match but returns the
// start and end indexes for the match instead of the
// matching text.
preg_match('/p([a-z]+)ch/', 'peach punch', $matches, PREG_OFFSET_CAPTURE);
echo "idx: [" . $matches[0][1] . " " . ($matches[0][1] + strlen($matches[0][0])) . "]\n";

// The preg_match function includes information about
// both the whole-pattern matches and the submatches
// within those matches.
preg_match('/p([a-z]+)ch/', 'peach punch', $matches);
print_r($matches);

// To find all matches for a regexp, use preg_match_all.
preg_match_all('/p([a-z]+)ch/', 'peach punch pinch', $matches);
print_r($matches[0]);

// Providing a limit to preg_match_all will limit the number
// of matches.
preg_match_all('/p([a-z]+)ch/', 'peach punch pinch', $matches, PREG_SET_ORDER, 2);
print_r($matches);

// The preg_replace function can be used to replace
// subsets of strings with other values.
$result = preg_replace('/p([a-z]+)ch/', '<fruit>', 'a peach');
echo $result . "\n";

// The preg_replace_callback function allows you to transform matched
// text with a given function.
$result = preg_replace_callback('/p([a-z]+)ch/', function($matches) {
    return strtoupper($matches[0]);
}, 'a peach');
echo $result . "\n";

To run the program, save it as regular-expressions.php and use php:

$ php regular-expressions.php
true
peach
idx: [0 5]
Array
(
    [0] => peach
    [1] => ea
)
Array
(
    [0] => peach
    [1] => punch
    [2] => pinch
)
Array
(
    [0] => Array
        (
            [0] => peach
            [1] => ea
        )

    [1] => Array
        (
            [0] => punch
            [1] => un
        )

)
a <fruit>
a PEACH

For a complete reference on PHP regular expressions, check the PHP Manual for PCRE functions.