如何使用PHP的str_replace移除文本及XML中的 字符
Ah, I see the issue here! When you're using DOMXPath to extract text content from XML/HTML, the entity (which represents a carriage return, CR) gets automatically parsed into an actual carriage return character (\r) by the DOM parser. That's why your current str_replace(" ", "", $desc) isn't working—there's no literal string left in the nodeValue anymore; it's been converted to the raw character.
Correct Approach for DOM Parsed Content
You need to target the actual carriage return character (\r) instead of the entity string. Here's how to adjust your code:
// Your existing code to retrieve the text node $c = $xpath->query("div[@class = 'show']/text()", $container)->item(0); $desc = $c->nodeValue; // Replace the raw carriage return character (\r) $desc = str_replace("\r", "", $desc); echo $desc;
Bonus: Handling Raw XML Strings (Before Parsing)
If you're working directly with the unparsed XML string (before feeding it into DOMXPath), you can still use the entity string in str_replace like this:
$rawXml = '<programme start="20180124160000 +0200" stop="20180124164500 +0200" channel="506"><title lang="he"> ריזולי ואיילס 7 11. הגופה</title><desc lang="he"> מתח. 11. הגופה: גופתו של קברן נמצאת בתוך ארון קבורה של אחד מלקוחותיו והדבר מוביל את חברי הצוות לחשיפת גופות נוספות. ג\'יין מבשרת לקרוביה על החלטתה לעבור לאף.בי.איי.</desc></programme>'; // Remove the entities directly from the raw string $cleanXml = str_replace(" ", "", $rawXml); // Now you can parse $cleanXml with DOMXPath if needed
Why This Works
- When DOM parses the XML, it resolves character entities to their corresponding ASCII/Unicode characters. So
becomes\r(carriage return) in the node's text value. - Targeting
\rdirectly instr_replaceensures you're removing the actual character that's present in your$descvariable.
内容的提问来源于stack exchange,提问作者dizzy

