简体   繁体   English

PHP检查它是否为有效的HTML属性

[英]PHP check if it is a valid HTML attribute

I would like to check if a given string could be a valid HTML attribute. 我想检查给定的字符串是否可以是有效的HTML属性。 If this isn't the case, I will add that string with a prefix of data- to the element. 如果不是这种情况,我会将带有data-前缀的字符串添加到元素中。 How would I go about this? 我将如何处理?

For example when the user wants to add a attribute, it passes it to the $attributes array like this: 例如,当用户想要添加属性时,将其传递给$attributes数组,如下所示:

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

So this will finally be added to a form element like an input or textarea or something like that. 因此,最终将其添加到诸如inputtextarea类的表单元素中。

... how would the implementation of is_attr($key) look like? ... is_attr($key)的实现如何?

Update: I was hoping I could create the attribute with the DomDocument() class and then validate it to see if the attribute is officially supported. 更新:我希望可以使用DomDocument()类创建该属性,然后对其进行验证以查看该属性是否受正式支持。 No luck so far. 到目前为止没有运气。

Here is is_attr function to check valid attributes of input or textarea. 这是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');

I have taken all the valid attributes from official html doc . 我已经从官方html doc中获取了所有有效属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM