How to write a regular expression in php?

by giovanny.lueilwitz , in category: PHP General , a year ago

How to write a regular expression in php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by filiberto , a year ago

@giovanny.lueilwitz 

To write a regular expression in PHP, you can use the preg_match() function. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
$pattern = '/^Hello, (.*?)!$/';
$string = 'Hello, John!';

if (preg_match($pattern, $string, $matches)) {
    echo 'Match found!';
    echo 'Matched string: ' . $matches[0]; // Output: Hello, John!
    echo 'Matched name: ' . $matches[1]; // Output: John
} else {
    echo 'No match found!';
}


In this example, the regular expression pattern '/^Hello, (.*?)!$/' is used to match strings that start with "Hello, ", followed by any name (captured as a group), and end with "!". The (.*?) is a non-greedy matching group that captures any characters between "Hello, " and "!".


preg_match() returns 1 if a match is found, and the matches are stored in the $matches array. You can access the matched groups using the indices in the array.