How to clear preg_match_all from empty array values

旧城冷巷雨未停 提交于 2019-12-11 12:58:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!