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条)

报告相同问题?