Encoding issue, coverting & to & for html using php

痴心易碎 提交于 2020-01-12 13:59:44

问题


I have a url in html:

<a href="index.php?q=event&amp;id=56&amp;date=128">

I need to turn it into a string exactly as:

<a href="index.php?q=event&id=56&date=128">

I know how to do this with preg_replace etc, but is there a function in php that deals directly with encoding that I can use for other encoding issues such as &nsbp (or whatever it is, etc)? Ideally I would send my string into the function and it would output '&' instead of &amp. Is there a universal function for converting &TEXT; into an actual character?

Edit: sorry, posted this before I finished typing the question. QUESTION is now complete.


回答1:


use html_entity_decode():

$newUrl = html_entity_decode('<a href="index.php?q=event&amp;id=56&amp;date=128">');
echo $newUrl; // prints <a href="index.php?q=event&id=56&date=128">



回答2:


Use htmlspecialchars_decode. Example straight from the PHP documentation page:

$str = '<p>this -&gt; &quot;</p>';
echo htmlspecialchars_decode($str); // <p>this -> "</p>



回答3:


There is no built in PHP function that will take an entity such as &amp; and turn it into a double &. Just in case there is any confusion, the html entity for & is actually &amp;, not amp;, so running any built in parser on your example will return the following:

<a href="index.php?q=event&id=56&date=128">

and not

<a href="index.php?q=event&&id=56&&date=128">

In order to get the double & version, you will need to use a regular expression.

Alternatively, if you in fact want the single & version, you have two possibilities.

  1. If you just wish to convert &amp; &quot; &#039; &lt; &gt; then you should use htmlspecialchars_decode. This would be sufficient for the example you give.
  2. If you wish to convert any string of the format &TEXT; then you should use html-entity-decode.

I suspect that htmlspecialchars_decode will be faster than html_entity_decode so if it covers all the entities you wish to convert, you should use that.




回答4:


after string go through TinyMCE only this code help me

$string = iconv('UTF-8','cp1251',$string);
$string = str_replace(chr(160), chr(32), $string);
$string = iconv('cp1251','UTF-8',$string);


来源:https://stackoverflow.com/questions/3516949/encoding-issue-coverting-amp-to-for-html-using-php

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