问题
I am using preg_match_all to build the array for shortcodes and it works fine but it also returns arrays with empty values see here please
https://eval.in/141437
Using this match witch I am sure is casuing the extra empty arrays
#\[link(.*?)link\=\"(.*?)\"(.*?)text\=\"(.*?)\"\]#e
How can I clear those. I tried array_filter but it did not work.
Thank you!
回答1:
()
represent a capture group and will be represented in the $matches
array even if it is empty.
Either get rid of the ()
around the groups that are returning empty like (.*?)
to make it just .*?
(because presumably you don't want those returned) or tell the engine not to capture that with (?:
like (?:.*?)
.
#\[link.*?link\=\"(.*?)\".*?text\=\"(.*?)\"\]#e
Or if you do want those returned when they are not empty, then use +
instead of *
:
#\[link(.+?)link\=\"(.*?)\"(.+?)text\=\"(.*?)\"\]#e
回答2:
The array_filter() function should work if you use it like this:
$matches = array_filter($matches, function($item) { return trim($item[0]) && true; });
AbraCadaver's answer is the best way to go.
来源:https://stackoverflow.com/questions/23280335/how-to-clear-preg-match-all-from-empty-array-values