php - 正则表达式 - 将 HTML 转换为有效的 XML 标记

标签 php regex

<分区>

我需要帮助编写一个将 HTML 字符串转换为有效 XML 标记名称的正则表达式函数。例如:它接受一个字符串并执行以下操作:

  • 如果字符串中出现字母或下划线,则保留
  • 如果出现任何其他字符,则会将其从输出字符串中删除。
  • 如果单词或字母之间出现任何其他字符,则将其替换为下划线。
Ex:
Input: Date Created
Ouput: Date_Created

Input: Date<br/>Created
Output: Date_Created

Input: Date\nCreated
Output: Date_Created

Input: Date    1 2 3 Created
Output: Date_Created

基本上,regex 函数应该将 HTML 字符串转换为有效的 XML 标记。

最佳答案

一些正则表达式和一些标准函数:

function mystrip($s)
{
        // add spaces around angle brackets to separate tag-like parts
        // e.g. "<br />" becomes " <br /> "
        // then let strip_tags take care of removing html tags
        $s = strip_tags(str_replace(array('<', '>'), array(' <', '> '), $s));

        // any sequence of characters that are not alphabet or underscore
        // gets replaced by a single underscore
        return preg_replace('/[^a-z_]+/i', '_', $s);
}

关于php - 正则表达式 - 将 HTML 转换为有效的 XML 标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10867836/

相关文章:

php - Cookie 不起作用

php - 在 linux 上将 php 模块与 .so 库链接

php - 组合正则表达式以将驼峰式字符串拆分为单词

regex - 有人能为我解释一下下面的正则表达式吗?

jquery - if 语句 - 仅接受字母的字段

php - 如何重定向到 PHP Soap 服务器中的页面

PHP 将数组作为字符串插入 mysql 文本字段

php - Opencart 3 .x SEO Url 不适用于 route=information/contact, route=account/login

java - 将输出分成 4 张椅子和蛮力方法的 block

regex - 使用 logback.xml 中的 replace(p){r, t} 转换将 '~' 替换为换行符 ('\n' )