Preg 替换锚标题属性

Preg Replace Anchor Title Attribute

我在包含 HTML 的锚点中有一个 title="" 属性。我正在尝试完全删除 title 属性,但无论出于何种原因,我正在使用的 preg 替换都不起作用。我试过:

$output = preg_replace( '/title=\"(.*?)\"/',  '', $output );
$output = preg_replace( '/\title="(.*?)"/',   '', $output );
$output = preg_replace( '` title="(.+)"`',    '', $output );

None 上面的作品,但我可以使用类似的东西:

$output = str_replace( 'title', 'class', $output );

只是为了证明我能够做某事(而且我没有上传错误的文件或其他东西)。输出如下所示:

<a href="#" title="<table border=\&quot;0\&quot; width=\&quot;100%\&quot; cellspacing=\&quot;0\&quot; cellpadding=\&quot;0\&quot;>
    <tbody>
        <tr>
            <td colspan=\&quot;2\&quot; align=\&quot;center\&quot; valign=\&quot;top\&quot;></td>
        </tr>
        <tr>
            <td valign=\&quot;top\&quot; width=\&quot;50%\&quot;>
            table content
            </td>
            <td valign=\&quot;top\&quot; width=\&quot;50%\&quot;>
            table content
            </td>
        </tr>
    </tbody>
</table>">Link Title</a>

所以我想做的是过滤 $output 并完全删除 title 属性,包括 title 属性中的所有内容。为什么上面的 preg_replace() 不起作用,我有什么选择?

不会使用正则表达式对[x]html进行操作,我会使用html解析器。

但是如果您仍然想使用正则表达式,那么您可以像这样使用正则表达式:

title="[\s\S]*?"

Working demo

你可以有这个代码:

$re = "/title=\"[\s\S]*?\"/"; 
$str = "<a href=\"#\" title=\"<table border=\&quot;0\&quot; width=\&quot;100%\&quot; cellspacing=\&quot;0\&quot; cellpadding=\&quot;0\&quot;>\n    <tbody>\n        <tr>\n            <td colspan=\&quot;2\&quot; align=\&quot;center\&quot; valign=\&quot;top\&quot;></td>\n        </tr>\n        <tr>\n            <td valign=\&quot;top\&quot; width=\&quot;50%\&quot;>\n            table content\n            </td>\n            <td valign=\&quot;top\&quot; width=\&quot;50%\&quot;>\n            table content\n            </td>\n        </tr>\n    </tbody>\n</table>\">Link Title</a>"; 
$subst = ""; 

$result = preg_replace($re, $subst, $str);

更新: 你可以在 Andrei P.[ 中看到一个清楚的例子,说明为什么你不应该使用正则表达式来解析 html =31=]评论