[英]PHP check if it is a valid HTML attribute
我想检查给定的字符串是否可以是有效的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()
类创建该属性,然后对其进行验证以查看该属性是否受正式支持。 到目前为止没有运气。
这是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中获取了所有有效属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.