Regex
PHP String Function: Regex
Categories:
preg_match()
preg_match(
string $pattern
,string $subject
,array &$matches = null
,int $flags = 0
,int $offset = 0
):int|false
Perform a regular expression match
preg_match('/(foo)(bar)(baz)/', 'foobarbaz', $matches, PREG_OFFSET_CAPTURE);
print_r($matches);
// Array
// (
// [0] => Array
// (
// [0] => foobarbaz
// [1] => 0
// )
// [1] => Array
// (
// [0] => foo
// [1] => 0
// )
// [2] => Array
// (
// [0] => bar
// [1] => 3
// )
// [3] => Array
// (
// [0] => baz
// [1] => 6
// )
// )
preg_match_all()
preg_match_all(
string $pattern
,string $subject
,array &$matches = null
,int $flags = 0
,int $offset = 0
):int|false
preg_match_all(
'/(?J)(?<match>foo)|(?<match>bar)/',
'foo bar',
$matches,
PREG_PATTERN_ORDER
);
print_r($matches['match']);
// Array
// (
// [0] =>
// [1] => bar
// )
preg_replace()
preg_replace(
string|array $pattern
,string|array $replacement
,string|array $subject
,int $limit = -1
,int &$count = null
):string|array|null
Perform a regular expression search and replace
$string = 'April 15, 2003';
$pattern = '/(\w+) (\d+), (\d+)/i';
$replacement = '${1}1,$3';
echo preg_replace($pattern, $replacement, $string);
// April1,2003
preg_split()
preg_split(
string $pattern
,string $subject
,int $limit = -1
,int $flags = 0
):array|false
Split string by a regular expression
$keywords = preg_split("/[\s,]+/", "hypertext language, programming");
print_r($keywords);
// Array
// (
// [0] => hypertext
// [1] => language
// [2] => programming
// )
preg_quote()
preg_quote(
string $str
,?string $delimiter = null
):string
Quote regular expression characters
$keywords = '$40 for a g3/400';
$keywords = preg_quote($keywords, '/');
echo $keywords; // returns \$40 for a g3\/400