How can I remove attributes from an html tag?

前端 未结 6 445
醉梦人生
醉梦人生 2020-11-29 09:52

How can I use php to strip all/any attributes from a tag, say a paragraph tag?

to

6条回答
  •  广开言路
    2020-11-29 10:09

    Here is one function that will let you strip all attributes except ones you want:

    function stripAttributes($s, $allowedattr = array()) {
      if (preg_match_all("/<[^>]*\\s([^>]*)\\/*>/msiU", $s, $res, PREG_SET_ORDER)) {
       foreach ($res as $r) {
         $tag = $r[0];
         $attrs = array();
         preg_match_all("/\\s.*=(['\"]).*\\1/msiU", " " . $r[1], $split, PREG_SET_ORDER);
         foreach ($split as $spl) {
          $attrs[] = $spl[0];
         }
         $newattrs = array();
         foreach ($attrs as $a) {
          $tmp = explode("=", $a);
          if (trim($a) != "" && (!isset($tmp[1]) || (trim($tmp[0]) != "" && !in_array(strtolower(trim($tmp[0])), $allowedattr)))) {
    
          } else {
              $newattrs[] = $a;
          }
         }
         $attrs = implode(" ", $newattrs);
         $rpl = str_replace($r[1], $attrs, $tag);
         $s = str_replace($tag, $rpl, $s);
       }
      }
      return $s;
    }
    

    In example it would be:

    echo stripAttributes('

    ');

    or if you eg. want to keep "class" attribute:

    echo stripAttributes('

    ', array('class'));

    Or

    Assuming you are to send a message to an inbox and you composed your message with CKEDITOR, you can assign the function as follows and echo it to the $message variable before sending. Note the function with the name stripAttributes() will strip off all html tags that are unnecessary. I tried it and it work fine. i only saw the formatting i added like bold e.t.c.

    $message = stripAttributes($_POST['message']);
    

    or you can echo $message; for preview.

提交回复
热议问题