简体   繁体   中英

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:

$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. A regular expression is not really suitable for your needs.

If it's properly formed, you could even use an xml parser. But you'd need all tags opened and closed first (or some in this way: < /br> ). Then, you can parse the xhtml with php as regular xml.

EDITED: Possible duplicate of Highlight text, except html tags

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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