【问题标题】:How can I remove all html tags from an array?如何从数组中删除所有 html 标签?
【发布时间】:2015-12-13 09:26:26
【问题描述】:

php 中有一个函数可以对数组的所有条目执行正则表达式替换操作吗?
我有一个数组,其中包含许多带有文本的 html 标签,我想删除这些标签。
所以基本上我正在转换这个:

$m = [
"<div>first string </div>",
"<table>
   <tr>
     <td style='color:red'>
       second string
     </td>
   </tr>
 </table>",
"<a href='/'>
   <B>third string</B><br/>
 </a>",
];

到这里:

$m = [
"first string",
"second string",
"third string"
]

(希望)匹配我要删除的所有内容的正则表达式如下所示:

/<.+>/sU

问题是我现在应该如何使用它? (我的数组实际上有 50 多个条目,每个条目中可能有 10 个匹配项,所以使用 preg_replace 可能不是要走的路,不是吗?)

【问题讨论】:

标签: php html arrays regex string


【解决方案1】:

这里不需要正则表达式,只需使用strip_tags() 删除所有html标签,然后简单地trim() 输出,例如

$newArray = array_map(function($v){
    return trim(strip_tags($v));
}, $m);

【讨论】:

    【解决方案2】:

    如果您想要正则表达式方法,您可以简单地执行以下操作:

    $array = preg_replace("/<.+>/sU", "", $array);
    

    【讨论】:

      【解决方案3】:

      array_map()strip_tags()

      $m = array_map( 'strip_tags', $m );
      

      修剪的原理相同。

      【讨论】:

        【解决方案4】:

        这里是带有对象检查的多维数组的变体

        
        /**
             * @param array $input
             * @param bool $easy einfache Konvertierung für 1-Dimensionale Arrays ohne Objecte
             * @param boolean $throwByFoundObject
             * @return array
             * @throws Exception
             */
            static public function stripTagsInArrayElements(array $input, $easy = false, $throwByFoundObject = true)
            {
                if ($easy) {
                    $output = array_map(function($v){
                        return trim(strip_tags($v));
                    }, $input);
                } else {
                    $output = $input;
                    foreach ($output as $key => $value) {
                        if (is_string($value)) {
                            $output[$key] = trim(strip_tags($value));
                        } elseif (is_array($value)) {
                            $output[$key] = self::stripTagsInArrayElements($value);
                        } elseif (is_object($value) && $throwByFoundObject) {
                            throw new Exception('Object found in Array by key ' . $key);
                        }
                    }
                }
                return $output;
            }
        
        

        【讨论】:

          猜你喜欢
          • 2012-10-11
          • 2011-03-02
          • 2019-03-04
          • 2013-04-28
          • 2015-10-09
          • 1970-01-01
          • 2014-03-14
          • 2011-07-31
          • 1970-01-01
          相关资源
          最近更新 更多