How to convert special characters in HTML using PHP?

我的梦境 提交于 2019-12-25 03:19:07

问题


Im looking to convert special characters like smart quotes to HTML entities but without converting other HTML markup because I need HTML markup to work. For example, convert <div>NVH “noise”</div> to <div>NVH &ldquo;noise&rdquo; issues<div>

Its strange that if I log this on my local environment I get “noise” with smartquotes but on server I got ?noise?. My local runs LAMP with php56. server ran 54 and 55. I upgraded to 56 still no luck. I think either something in php configuration or among other things. Same exact code.


回答1:


For only one translation of the smart quotes, or for some characters and not others, str_replace is probably the only way to go:

$string = str_replace(array('“','”'), array('&ldquo;','&rdquo;'), $string);



回答2:


Try php htmlspecialchars method

<?php
$new = htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES);
echo $new; // &lt;a href=&#039;test&#039;&gt;Test&lt;/a&gt;     
?>


来源:https://stackoverflow.com/questions/28885466/how-to-convert-special-characters-in-html-using-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!