簡體   English   中英

在轉義斜杠時將 unicode 特殊字符轉換為 html 的最佳方法?

[英]Best way to convert unicode special characters to html while escaping slashes?

所以我發現我自己需要轉換一些來自數據庫的 html 文本,我得到類似於這些的字符串:

<p style=\"font-size: 10px;\">\n<strong>Search for:<\/strong> <span style=\"color:#888888;\">2 to 15 People, \u00b120$ Per Person, Informal, Available on Date<\/span>\n<\/p>

我需要把它放在適當的 HTML 中。 像這樣的東西:

<p style="font-size: 10px;">
<strong>Search for:</strong> <span style="color:#888888;">2 to 15 People, &plusmn;20$ Per Person, Informal, Available on Date</span>
</p>

這里有幾個問題,首先是斜杠,我在stripslashes之前使用stripcslashes,所以它首先轉換像“\\n”這樣的C風格轉義符。 然后我使用stripslashes刪除引號轉義。 但這會弄亂像 ± 符號 (\±) 這樣的 unicode 字符

我在網上搜索過,似乎使用 json decode 是通常用於此的技巧,但由於我正在使用的字符串類型,我不能在這里使用 json decode。 這只是一個例子,我使用的真正字符串是完整的 HTML 頁面。

有沒有人有任何提示我如何解決這個問題?

這是我目前正在使用的:現在我正在使用這個:

$final = urlencode(stripslashes(stripcslashes(html_entity_decode($html, ENT_COMPAT, 'UTF-8'))));

它為我提供了一個幾乎完美的 HTML 頁面,除了像 \± 這樣的 unicode 字符

解決方案

我最終使用了 Lawrence Cherone 給出的解決方案

$new_html = str_replace(array('\"', '\/', '&quot;', '\n'), array('"', '/', '\'', "\n"), $old_html);

function unicode_convert($match){
   return mb_convert_encoding(pack('H*', $match[1]), 'UTF-8', 'UCS-2BE');                         }                          

$new_html = preg_replace_callback('/\\\\u([0-9a-fA-F]{4})/', "unicode_convert", $new_html);

如果我理解正確,您只是想切換: \\"代表"\\/代表/ ,也許還有其他人。

您可以使用str_replace()並在要切換的事物列表中定位超過\\

編輯,使用以下答案中的 preg_replace_callback 代碼修復 unicodes: 如何將 Unicode 轉義序列(如“\í”)解碼為正確的 UTF-8 編碼字符?

<?php
$str = '<p style=\"font-family: &quot;Open Sans&quot;, sans-serif; font-size: 10px; color: rgb(60, 170, 80); line-height: 150%; text-align: right; padding-top: 0px; padding-bottom: 0px; margin: 0px; overflow: hidden;\"><strong>Search for:<\/strong> <span style=\"color:#888888;\">2 to 15 People, \u00b120$ Per Person, Informal, Available on Date<\/span>\n<\/p>';

echo preg_replace_callback('/\\\\u([0-9a-fA-F]{4})/', function ($match) {
    return mb_convert_encoding(pack('H*', $match[1]), 'UTF-8', 'UCS-2BE');
}, str_replace(['\"', '\/', '&quot;', '\n'], ['"', '/', '\'', "\n"], $str));

結果:

<p style="font-family: 'Open Sans', sans-serif; font-size: 10px; color: rgb(60, 170, 80); line-height: 150%; text-align: right; padding-top: 0px; padding-bottom: 0px; margin: 0px; overflow: hidden;"><strong>Search for:</strong> <span style="color:#888888;">2 to 15 People, ±20$ Per Person, Informal, Available on Date</span>
</p>

https://3v4l.org/fTtLh

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM