簡體   English   中英

如何在php和sql中進行特殊字符轉換?

[英]How can I do special characters conversion in php and sql?

我正在學習curl以從站點獲取數據。 除特殊字符外,Curl都可以正常工作。 當我查看網站的來源時,它包含以下項目。

<li class="page_item page-item"><a href="../categories/mens-health/">Men&#8217;s Health</a></li>
<li class="page_item page-item"><a href="../categories/nails-hair-skin/">Nails, Hair &#038; Skin</a></li>
<li class="page_item page-item"><a href="../categories/womens-health/">Women’s Health</a></li>  

當我得到數組中的數據並在瀏覽器上回顯它時,結果為

Men&#8217;s Health  
Nails, Hair &#038; Skin  
Women’s Health

我通過執行以下代碼獲得

$search = array('&#146;');
$replace = array("'");  
$category_names[] = htmlentities(str_replace($search, $replace, $word), ENT_QUOTES);

$ word是上面的3個數組項。 現在,在插入數據庫時​​,我無法將它們轉換為正確的字符。 這是它出現在我的數據庫中的方式

Men&amp;#8217;s Health
Nails, Hair &amp;#038; Skin
Women&rsquo;s Health

如何按以下正確格式插入它?
男性健康
指甲 頭發和皮膚
女性健康

我檢查了一些具有撇號的解決方案,但它們大多是單個插入語句,就像我在循環中插入的那樣。

將帶有'(撇號)的文本插入SQL表的方法
如何在SQL Server中轉義單引號?

我做了html_entity_decode($ category_names [$ i]); 現在我在數據庫中得到以下結果
男性健康
指甲,頭發和皮膚
婦女的健康

html_entity_decode將解碼HTML實體,包括NCR 例如, &#8217; 會變成'

<?php
$in = 'Men&#8217;s Health  
Nails, Hair &#038; Skin  
Women’s Health';

echo html_entity_decode($in);

將打印

Men’s Health  
Nails, Hair & Skin  
Women’s Health

上面的代碼托管在這里: http : //ideone.com/1rWL45

編輯

您的數據庫表可能位於Latin1中,並且在其中插入Unicode(例如' )字符會導致此類字符混亂。 只需將幾個Unicode字符替換為ASCII可能會減輕編碼問題的某些部分。 但是,我建議將表的字符集更改為UTF-8。

<?php

$map = [ '’' => "'", "..." => "..." ]; // from->to pairs
$normalized = str_replace(array_keys($map), array_values($map), $string);

可能是.html和.text函數可以為您提供幫助,例如:

html

<div id="test">&lt;&lt;</div>

jQuery的

var t = $('#test');
t.html(t.text());

也許這可以幫助您js小提琴鏈接

某些字符在HTML中具有特殊意義,如果要保留其含義,則應由HTML實體表示。 該函數返回一個字符串,其中包含一些轉換。 所做的翻譯對於日常Web編程最有用。 如果您需要翻譯所有HTML字符實體,請改用htmlentities()

htmlspecialchars —將特殊字符轉換為HTML實體

string htmlspecialchars ( string $string [, int $flags = ENT_COMPAT | ENT_HTML401 [, string $encoding = ini_get("default_charset") [, bool $double_encode = true ]]] )

如果傳遞給此函數的輸入字符串和最終文檔共享相同的字符集,則此函數足以准備將輸入包含在HTML文檔的大多數上下文中。 但是,如果輸入可以表示未在最終文檔字符集中編碼的字符,而您希望保留這些字符(作為數字或命名實體),則此函數和htmlentities() (僅對具有命名實體的子字符串進行編碼htmlentities()等值)可能不足。 您可能不得不使用mb_encode_numericentity()

執行的翻譯是:

'&' (ampersand) becomes '&amp;'
'"' (double quote) becomes '&quot;' when ENT_NOQUOTES is not set.
"'" (single quote) becomes '&#039;' (or &apos;) only when ENT_QUOTES is set.
'<' (less than) becomes '&lt;'
'>' (greater than) becomes '&gt;'

暫無
暫無

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

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