preg_grep – find keys in an array that match a pattern

Sometimes there is a need to find a key/s of an array that matches a particular pattern. array_search searches the array for a given value and returns the corresponding key but it matches the entire word.

Here’s a scenario. You have a list of tags and you want to provide a user to seach a particular tag which closely matches to their search.

So here are some of the tags in an array

If the user enters WordPress we want to show WordPress Plugins as well as WordPress Tweaks. So this is how it can be done using preg_grep

where $key is the user input i.e. WordPress in this case

In our case $filtered_tags will be an array and will return

0=>Wordpress Plugins

1=>Wordpress Tweaks

 

Create wordpress plugin for custom PHP code

Often there is requirement to create your own PHP application and generally most people tend to install a plugin which allows to run PHP code snippets as it is much easier to do so.
Although this approach may seem ok it may not be ideal. Lot of times people use this approach because they do not know how to create plugin for the same in WordPress.

Actually it is much easier to create wordpress plugin than you think.
I understand it may take a bit longer to create a plugin than just writing a PHP code snippet. However the difference is not that big.

Creating your own WordPress plugin for your requirement works out better in the long run

  1. It allows you to deactivate as soon as you feel you do not need the code to run on your site
  2. You are in total control of the code.
  3. If the PHP plugin which allows you to run your PHP code snippets stops providing support or is no longer maintained then you need to find another plugin and move all your code to the other plugin. This means lot of your applications may break in the meantime.

Here is one simple solution to create wordpress plugin to run our small PHP code snippet.

  1. First of all create a folder in your plugin folder where the plugin files will reside e.g. my_php_code_snippet
  2. Create a main plugin file inside the folder called as plugin.php with below content
  3. Now create a file named my_php_code_snippet_class.php in the same folder with below contents

    If you want the snippet to be executed only for logged in users just add is_user_logged_in condition
  4. Activate the plugin
  5. Finally add the shortcode [PHP_CODE_SNIPPET_1] on the page on which you wish to execute the PHP code snippet