首页 > 解决方案 > PHP 检查它是否是一个有效的 HTML 属性

问题描述

我想检查给定的字符串是否可以是有效的 HTML 属性。data-如果不是这种情况,我将在元素中添加带有前缀的字符串。我该怎么办?

例如,当用户想要添加一个属性时,它会将其传递给$attributes数组,如下所示:

    $attr = '';
    foreach ( $attributes as $key => $value ) {
        if (is_attr($key)) {
            $attr .= $key . '="' . $value . '" ';
        } else {
            $attr .= 'data-' . $key . '="' . $value . '" ';
        }
    }

所以这最终将被添加到一个表单元素中,比如一个input或类似的textarea东西。

... 的实施情况如何is_attr($key)

更新: 我希望我可以使用DomDocument()该类创建属性,然后验证它以查看该属性是否得到官方支持。到目前为止没有运气。

标签: phphtmldom

解决方案


这是is_attr检查输入或文本区域的有效属性的功能。

function is_attr($attr, $elementType)
{
    $input       = ["autocomplete", "autofocus", "disabled", "list", "name", "readonly", "required", "tabindex", "type", "value"];
    $globalAttrs = ["accesskey", "class", "contenteditable", "contextmenu", "dir", "draggable", "dropzone", "id", "lang", "style", "tabindex", "title", "inputmode", "is", "itemid", "itemprop", "itemref", "itemscope", "itemtype", "lang", "slot", "spellcheck", "translate"];
    $select      = ["autofocus", "disabled", "form", "multiple", "name", "required", "size"];
    $textarea    = ["autocapitalize", "autocomplete", "autofocus", "cols", "disabled", "form", "maxlength", "minlength", "name", "placeholder", "readonly", "required", "rows", "spellcheck", "wrap"];
    return (in_array($attr, $globalAttrs) || in_array($attr, $$elementType));
}
echo is_attr('accesskey','select');

我已从官方 html doc中获取所有有效属性。


推荐阅读