Hex-to-Numeric Entities Converter

At work I get files sometimes with hexadecimal entities but the problem is that we use numeric entities. I decided to write a simple script that will search the file for hex entities and convert them to numeric one. This is intended to be used with Komodo Edit or via the command line.


This is the command that needs to be added to Komodo Edit.
%(php)" -f "C:\Users\JayBachatero\Desktop\hex-to-numeric.php" -- --filename="%F"

To add the command in KE, all you need to do is:

  1. Go to Toolbox > Add > New Command
  2. In the first text area the following text appear, “New Command”, replace that with the name that you want to give this command. ie “Hex to Numeric”
  3. In the command field, you enter the command shown above. Make sure that the path to the file is correct.
  4. Select “Command Output Tab” under the “Run in” section.

If you want to see the results of the command, uncheck “Do not open output pane”.

Here is the code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
< ?php
 
$filename = substr($_SERVER['argv'][1], 11);
$lines = file($filename);
 
foreach ($lines as $key => $line)
{
	// Lets get the lines with hex chars in it.
	if (preg_match('~&#x([0-9a-fA-F]+);~', $line, $matches))
	{
		echo 'Found: &#x' . $matches[1] . '; (' . chr(hexdec('0x' . $matches[1])) . '). Replaced: &#' . hexdec('0x' . $matches[1]) . ';' . "\n";
		$lines[$key] = str_replace('&#x' . $matches[1] . ';', '&#' . hexdec('0x' . $matches[1]) . ';', $lines[$key]);
		$lines[$key] = str_replace(array('&#62;', '&#60;'), array('&gt;', '&lt;'), $lines[$key]);
	}
}
 
// Lets save to a string.
$data = '';
foreach ($lines as $line)
	$data .= $line;
 
$saved = file_put_contents($filename, $data);
if ($saved == true)
	echo "\nSAVED";
else
	echo "\nCOULD NOT SAVE"
 
?>

Leave a Reply

Your email address will not be published. Required fields are marked *


*