Question

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!

Was it helpful?

Solution

() 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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top