John Smith
John Smith

Reputation: 6207

How to limit a string not to hurt HTML code, in Php?

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

Answers (3)

Ben
Ben

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

Matthew
Matthew

Reputation: 11

filter the string before cutting by using FILTER_SANITIZE_STRING

Upvotes: 1

Reger
Reger

Reputation: 474

These are the tools you can use to solve that out: substr() to find the position of the tags, strlen($string) to calculate the lenght of the string, and substr() to get the pieces of the string.

Upvotes: 1

Related Questions