Reputation: 6207
I have a big problem. I must cut a string which consists HTML code. But I have no idea how to do it so that HTML code wont get damage:
<p>this is a <strong>HTML</strong> code which is too long, and can be even UNICODE characters</p>
with mb_substr():
<p>this is a <strong>HTM
is there a way solving it out?
Upvotes: 0
Views: 89
Reputation: 401
You have to parse your string. I'd do something like a split using regex and then cut the string (count the characters without the tags) and then add closetags again.
Try this to cut after 10 characters and works only for the first occurence:
$cut_after = 10;
$string_complete = "<b>Peter Griffin</b>";
$string_to_cut = filter_var($string_complete, FILTER_SANITIZE_STRING);
var_dump($string_complete);
//string '<b>Peter Griffin</b>' (length=20)
$string_chopped_head = substr($string_to_cut, 0, $cut_after);
$string_chopped_tail = substr($string_to_cut, $cut_after, (strlen($string_to_cut)-$cut_after));
$string_head_before_cut = substr($string_complete, 0, stripos($string_complete, $string_chopped_head));
$string_tail_after_cut = substr($string_complete, stripos($string_complete, $string_chopped_tail)+strlen($string_chopped_tail));
$final_string = $string_head_before_cut . $string_chopped_head . $string_tail_after_cut;
var_dump($final_string);
//string '<b>Peter Grif</b>' (length=17)
Upvotes: 1