There are two ways of doing this:
You can decode the HTML entities, substr()
and then encode; or
You can use a regular expression.
(1) uses html_entity_decode()
and htmlentities()
:
$s = html_entity_decode($mytext);
$sub = substr($s, 0, 6);
echo htmlentities($sub);
(2) might be something like:
if (preg_match('!^([^&]|&(?:.*?;)){0,5}!s', $mytext, $match)) {
echo $match[0];
}
What this is saying is: find me up to 5 occurrences of the preceding expression from the beginning of the string. The preceding expression is either:
any character that isn't an ampersand; or
an ampersand, followed by anything up to and including a semi-colon (ie an HTML entity).
This isn't perfect so I would favour (1).