2016-05-12 8 views
1

私は、次の文字列を持っている:私は、HTMLエンティティに変換したいユニコード特殊文字をhtmlエンティティに変換するにはどうすればよいですか?

$string = "★ This is some text ★"; 

を:

$string = "★ This is some text ★"; 

ソリューション誰もがについて書いている:

htmlentities("★ This is some text ★", "UTF-8"); 

しかしにhtmlentitiesはできませんすべてのユニコードをHTMLエンティティに変換します。だから、それはちょうど私の入力と同じ出力が得られます。

★ This is some text ★ 

私も両方で、このソリューションを組み合わせることを試みた:

header('Content-Type: text/plain; charset=utf-8'); 

と:

mb_convert_encoding(); 

しかし、これをどちらか印刷して空の結果を表示したり、まったく変換したり、星を間違って変換したりします。

 

★と他のすべてのユニコード文字を正しいhtmlエンティティに変換する方法は?

+0

のhttp://をphp.net/manual/en/function.htmlentity.php#107985 – iainn

答えて

4

htmlentitiesは、このケースでは動作しませんが、あなたはUCS-4エンコードに文字列、のような何か試すことができます。

$string = "★ This is some text ★"; 
$entity = preg_replace_callback('/[\x{80}-\x{10FFFF}]/u', function ($m) { 
    $char = current($m); 
    $utf = iconv('UTF-8', 'UCS-4', $char); 
    return sprintf("&#x%s;", ltrim(strtoupper(bin2hex($utf)), "0")); 
}, $string); 
echo $entity; 

★ This is some text ★ 

Ideone Demo

関連する問題