PHP中如何将–转换为–?str_replace失效求助
Hey there! Let's break down why your str_replace isn't working and fix this up. The core issue here is almost certainly that the substring you're searching for doesn't match what's actually in your string—let's cover the common scenarios and their fixes:
Scenario 1: Your string contains the raw – entity
If your original string directly includes the – HTML entity (which renders as the en dash – when displayed), a straightforward str_replace will work:
$originalStr = "Pirate Code – PVP Battles at Sea Trailer"; $modifiedStr = str_replace('–', '–', $originalStr); // Result: "Pirate Code – PVP Battles at Sea Trailer"
Scenario 2: The – has already been decoded to the actual en dash character
If your string was already processed (e.g., pulled from a database that auto-decodes entities, or ran through htmlspecialchars_decode), the – is now the actual – character. Searching for the entity won't find anything—instead, match the character directly:
$originalStr = "Pirate Code – PVP Battles at Sea Trailer"; $modifiedStr = str_replace('–', '–', $originalStr);
Scenario 3: Your string has an escaped version of the entity (–)
Looking at your example string: "Pirate Code – PVP Battles at Sea Trailer", this means the actual stored value is –—which is the HTML-escaped version of – (it would render as – on a page, not the dash itself). In this case, you need to target the escaped entity:
$originalStr = "Pirate Code – PVP Battles at Sea Trailer"; $modifiedStr = str_replace('–', '–', $originalStr); // Result: "Pirate Code – PVP Battles at Sea Trailer"
A quick tip to debug: Use var_dump($originalStr) or check the raw source of your page to see exactly what's in the string—this will tell you which scenario you're dealing with.
内容的提问来源于stack exchange,提问作者Hasan Abbas

