简体   繁体   中英

Encoding issue, coverting & to & for html using php

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.

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">

Use htmlspecialchars_decode . Example straight from the PHP documentation page:

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

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; &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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM