简体   繁体   English

PHP:替换字符串中的双引号而不替换HTML标记中的双引号

[英]PHP: Replace Double Quotes in String But Not Those Within HTML Tag

Looking for the best solution on how to replace regular quotes within a block of text with curly quotes, but not to change quotes found within html tag markers <....> I have attempted using preg-replace, such as: 寻找有关如何用卷曲引号替换文本块中的常规引号,而不是更改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);

For example, if I have the following: 例如,如果我有以下内容:

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

I want it to end up as: 我希望它最终成为:

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

Use a HTML parser which allows you to access text nodes easily. 使用HTML解析器,它使您可以轻松访问文本节点。 A regular expression is not really suitable for your needs. 正则表达式并不真正适合您的需求。

If it's properly formed, you could even use an xml parser. 如果格式正确,您甚至可以使用xml解析器。 But you'd need all tags opened and closed first (or some in this way: < /br> ). 但是您需要首先打开和关闭所有标签(或者以这种方式一些: < /br> )。 Then, you can parse the xhtml with php as regular xml. 然后,您可以将xhtml与php解析为常规xml。

EDITED: Possible duplicate of Highlight text, except html tags 编辑: 高亮文本可能重复,但html标记除外

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM