php - 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()
该类创建属性,然后验证它以查看该属性是否得到官方支持。到目前为止没有运气。
解决方案
这是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中获取所有有效属性。
推荐阅读
- reactjs - Web 服务器包问题.. 未找到模块
- rest - Spring Security 403 http状态
- reactjs - React-scroll 改变 Link 元素的状态
- maven - 使用包含部分输入路径的输出路径复制资源
- vue.js - 在 VueX 中存储多个 Axios 请求的最佳方式是什么?
- c# - 将 JSON 更改为 JSON 数组(例如 [1,2,3])或更改反序列化类型,使其正常
- mongoose - 收到错误“throw new mongoose.Error.MissingSchemaError(name); MissingSchemaError:”
- scala - 如何在数据框中附加列值
- label - 自定义工具提示内容@ngx-charts | 角2+ | 打字稿
- python - 如何通过 cython 将 MPI 通信器从 python 传递到 C?