Search code examples
phpregexpcre

Regex extract characters between two string including delimiters


I'm trying to extract the text between two characters including the delimiters, but only the text without the delimiter is returned:

.+(?<=\()(.*?)(?=\))

See the current regex demo.

Example:
Some text (1990) (//Divulgação)

Should return:
(//Divulgação) (not //Divulgação)


Solution

  • You may extract those substrings between ( and ) using

    preg_match('~.*\K\([^()]*\)~s', $s, $matches)
    

    See the regex demo.

    Details

    • .* - any 0+ chars, as many as possible
    • \K - match reset operator that discards the text matched so far from the match buffer
    • \( - a ( char
    • [^()]* - 0+ chars other than ( and )
    • \) - a ) char.