Regex - optional value
preg_match_all('/<p class="row">(.+?)<\/span>(.+?)- <a href="(.+开发者_JAVA技巧?)">(.+?)<\/a>(.+?)<font size="-1"> \((.+?)\)<\/font>(.+?)<\/p>/is', $HTML, $matches);
I have the following regex, the problem is that only sometimes does the section actually show up. The regex I have requires the font to be there, how can I make it optional?
Not only mkae it optional, but pull a value if it exists
This is working for me:
(?:<font size="-1">(.+?)<\/font>)?
Further example:
% perl -e '$x = "ab<font size=\"-1\">foo</font>"; print "$1 $2" if $x =~ /(ab)(?:<font size="-1">(.+?)<\/font>)?/'
ab foo
% perl -e '$x = "ab<font size=\"-1\">foo</fontXXXXXXX>"; print "$1 $2" if $x =~ /(ab)(?:<font size="-1">(.+?)<\/font>)?/'
ab
You can make font optional like:
(<\/font>)?
精彩评论