Home >Backend Development >PHP Tutorial >How to Match Newline Characters Within `` Tags in Regular Expressions?
Matching Newline Characters in Regular Expressions
You have a string with characters, whitespace, and newlines between
Solution 1: DOTALL Modifier (s)
Use the DOTALL modifier (s), which makes the dot (.) match newlines:
'/<div>(.*)<\/div>/s'
Solution 2: Non-Greedy Match
To prevent greedy matching, use a non-greedy match with *?:
'/<div>(.*?)<\/div>/s'
Solution 3: Exclude < If Other Tags Are Not Present
You can match everything except < if there aren't other tags:
'/<div>([^<]*)<<\/div>/''
Note on Regex Delimiters
You can use characters other than / as regular expression delimiters, which allows for easier escaping of special characters:
'#<div>([^<]*)<<\/div>#'
Caution
These solutions may fail for nested divs, extra whitespace, HTML comments, and other complexities. Consider using an HTML parser for reliable HTML parsing.
The above is the detailed content of How to Match Newline Characters Within `` Tags in Regular Expressions?. For more information, please follow other related articles on the PHP Chinese website!