Saturday, August 24, 2013

strip selected html tags

Using strip_tags we can remove HTML element from a string. But we want to remove selected tags from a string. we can use regular expression to implement this feature.

The below regular expression provide us a way to remove the selected HTML tags from the string.
preg_match_all('/<'.$tag.'[^>]*>(.*)<\/'.$tag.'>/iU', $text, $found)

Then we replace the matched pattern with the matched text string of preg_match_all. The PREG_PATTERN_ORDER returns the matched tag pattern in the first array and returns text pattern on the second pattern.
$text = str_replace($found[0],$found[1],$text);
The complete function becomes like this:
function strip_selected_tags($text, $tags = array())
        foreach ($tags as $tag){
            if(preg_match_all('/<'.$tag.'[^>]*>(.*)<\/'.$tag.'>/iU', $text, $found)){
                $text = str_replace($found[0],$found[1],$text);

        return $text;

  echo htmlentities(strip_selected_tags('
Salavert', array('strong', 'div')));

See the book OpenCart 1.4 Template Design Cookbook.
See the book Joomla Mobile Development Beginners Guide

List of my works:

Opencart Extensions:

  1. Product Based Quantity Wise Shipping: Find it here.
  2. OpenSSLCOMMERZ: integrate SSLCOMMERZ with opencart: Find it here.
  3. Fine Search v.1.0 - Improves Opencart search feature to find relevant: Find it here.
  4. Opensweetcaptcha - An easy way to generate attractive captcha for your system!: Find it here.
  5. Custom Field Product - add unlimited custom fields to the product form: Find it here.
  6. Formcaptcha - add captcha on the register page: Find it here.

My Books:

  1. OpenCart 1.4 Template Design Cookbook.
  2. Joomla Mobile Development Beginners Guide

No comments: