【问题标题】:PHP: Replace Double Quotes in String But Not Those Within HTML TagPHP:替换字符串中的双引号,而不是 HTML 标记中的双引号
【发布时间】:2012-04-16 15:43:32
【问题描述】:

寻找关于如何用弯引号替换文本块中的常规引号的最佳解决方案,但不更改在 html 标记标记中找到的引号 <....> 我尝试使用 preg-replace,例如:

$pattern = '/(?<!=)"\b/';
$lyrics = preg_replace($pattern, "\u201c", $lyrics);
$pattern = '/\b"(?!>)/';
$lyrics = preg_replace($pattern, "\u201d", $lyrics);
$pattern = '/\."/'; // find regular quotes after a period
$lyrics = preg_replace($pattern, ".\u201d", $lyrics);
$pattern = '/\!"/'; // find regular quotes after an exclamation
$lyrics = preg_replace($pattern, "!\u201d", $lyrics);
$pattern = '/"\s/'; // find regular quotes before a space
$lyrics = preg_replace($pattern, "\u201d ", $lyrics);

例如,如果我有以下情况:

<a href="http://somelink.com">"This is a quotation."

我希望它最终成为:

<a href="http://somelink.com">“This is a quotation.”

【问题讨论】:

    标签: php regex preg-replace


    【解决方案1】:

    使用允许您轻松访问文本节点的 HTML 解析器。正则表达式是 not really suitable 以满足您的需要。

    【讨论】:

      【解决方案2】:

      如果格式正确,您甚至可以使用 xml 解析器。但是您需要首先打开和关闭所有标签(或者以这种方式:&lt; /br&gt;)。然后,您可以将parse the xhtml with php 作为常规 xml。

      已编辑:Highlight text, except html tags 可能重复

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-07
        • 2012-03-12
        • 2021-11-12
        • 2017-08-21
        • 1970-01-01
        相关资源
        最近更新 更多