Not how I can not understand how to use and why you need () in regulars. Can someone suggest and bring not a great example.

2 answers 2

Find, isolate certain groups of characters from strings. Tasks can be many.

For example, to find all the numbers that begin with "hello" end in "years", and in the middle there can be any numbers. Here you need to find all these numbers.

привет100лет а может привет80лет а может и привет666лет 

regular season

 /привет([0-9]+)лет/ 

eventually

 preg_match_all('/привет([0-9]+)лет/', 'привет100лет а может привет80лет а может и привет666лет', $matches, PREG_OFFSET_CAPTURE); foreach ($matches[1] as $match) { echo $match[0].'<br/>'; } 

will lead

 100 80 666 

Without group highlighting, a regular expression would produce a solid result, such as

 привет100лет привет80лет привет666лет 

But regular allocation of telephone numbers from the line:

 /\(? (\d{3})? \)? (?(1) [\-\s] ) \d{3}-\d{4}/x 

which is from a string

 Звоните 555-1212 или 1-800-555-1212 

reach groups:

 555-1212 800-555-1212 

    Preserving parentheses: (...) and \ 1, \ 2, ...

    Standard parentheses typically perform two functions: grouping and saving. They are almost always included in expressions in the form (...), but in a number of dialects, the notation \(…\) .

    Preserving brackets are identified by the ordinal number of the opening bracket from the left edge of the expression .

    If backlinks are supported in the dialect, then the text that matches the subexpression in parentheses can be referenced in the same regular expression using the \ 1 , \ 2 metacharacters, etc.

    Most often, parentheses are used to extract data from a string .