Organizational Research By

Surprising Reserch Topic

Experts Most Trusted Topic


boostr.in questions - Question:Extracting Data with preg_match()


Some basic examples

# Extract everything after the literal "START"
preg_match("/START(.*)/", $string, $results)   

# Extract the number from a date string
preg_match("/(\d{4})-(\d{2})-(\d{2})/", "2012-10-20", $results)

# Nesting of capture groups, extract full name, and both parts...
preg_match("/name is ((\w+), (\w+))/", "name is Doe, John", $results)

So you basically just enclose the sub patterns you want to extract with braces and fetch the results by passing a third parameter which preg_match() will fill as an array.

Named Capture Groups

# Extract the number from a date string
preg_match("/(?P\d{4})-(?P\d{2})-(?P\d{2})/", "2012-10-20", $results)

Now the $result array will additionally to the position matches 1, 2 and 3 contain the keys "year", "month" and "day". The advantage is never having to think of the capture positions anymore when you modify the expression!

asked Sep 13, 2013 in PHP by anonymous
edited Sep 12, 2013
0 votes
17 views



Related Hot Questions



Government Jobs Opening


...