The problem is that you are viewing the output in the browser window where output from htmlentities
(and equivalent functions) is rendered for display to an end user.
For example:
echo htmlentities("&");
Will output &
because it has converted the &
character to it's html entity equivalent. See that it is five characters long. However, you don't see the full text &
because you're viewing from your browser which has pre-rendered it as the &
symbol. In firfox if you right click the viewport and click on "View Page Source" you will see the full text &
...
Your code:
$a = htmlentities("&12345"); //Outputs: &12345
$b = substr($a, 0, 6); //Selects first six charachters: &, a, m, p, ; and 1
echo $b; // Echo's: &1 which is displayed by the browser as &1
To get around this you can change the order of your functions:
$a = substr("&12345", 0, 6);
echo htmlentities($a);