dpw5865 2015-07-23 15:41
浏览 47
已采纳

在PHP中组合标记的重复属性

I need to convert the string This <span style="font-size: 16px;" style="color: red;">is</span> a test. to This <span style="font-size: 16px; color: red;">is</span> a test.

There's also the possibility that there could be more than two matches or that there could be a style, then a class, then another style, and the styles would need to be combined. And they won't always be spans

Unfortunately Tidy isn't an option as it is more over-bearing in it's cleaning than this project can accommodate.

Going the DOM document route won't work since multiple style attributes isn't valid, so it only gets the contents of the first one.

I'd like to do it with preg_replace, but getting just the matches from one tag is proving to be quite difficult.

If it makes things easier, they start life as nested tags. I have a preg_replace that combines them from there and gives this output.

  • 写回答

3条回答 默认 最新

  • duanping6698 2015-07-23 16:02
    关注

    I agree with the comments above that the best solution is to prevent this situation in the first place, but to answer your question: This function will combine all of the style attributes in the given string. Just make sure to pass only a single tag at a time. It doesn't matter how many other attributes are in the tag, nor does the order matter. It will combine all of the style attributes into the first style value, then remove all other style attributes:

    /**
     * @param string $str
     * @return string
     */
    function combineStyles($str)
    {
        $found = preg_match_all("/style=\"([^\"]+)\"/", $str, $matches);
        if ($found)
        {
            $combined = 'style="' . implode(';', $matches[1]) . '"';
            $patterns = $matches[0];
            $replace = array_pad(array($combined), count($matches[0]), '');
            $str = str_replace($patterns, $replace, $str);
        }
        return $str;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c