Reputation: 33
My issue is, if the string contains an html tag, then the string should becropped in between the html elements. This is my code. I want to cut the string if string length is greater than 80. When I try to do this string is cropped in between these tags. This will affected css style issue. So string cropping should be only after end of the html tag.
<?php
echo $word='hello good morning<span class="em emj2"></span> <span class="em emj13"></span> <span class="em emj19"></span> <span class="em emj13"></span> hai';
$a=strlen($word);
if($a>80)
{
echo substr($word,0,80);
}
else
echo $word;
?>
Upvotes: 0
Views: 184
Reputation: 744
You could perform a second edit and use strrpos to find the last > and see if it is before the last < in the resulting string.
If so, cut back to before the last < to ensure you don't have a partial tag inclusion.
<?PHP
echo $word='hello good morning<span class="em emj2"></span> <span class="em emj13"></span><span class="em emj19"></span> <span class="em emj13"></span> hai';
echo "\n";
$a=strlen($word);
echo strlen($word);
echo "\n";
if($a>80) {
$b=substr($word,0,80);
echo "$b\n";
$end=strrpos($b,'>');
$start=strrpos($b,'<');
echo "> is $end from the end, < is $start from the end\n";
if($start > $end){
echo "cutting '$b' down to $end characters (+1 to keep the '>')\n";
$b=substr($b,0,$end+1);
}
echo "$b\n";
}
else {
echo $word."\n";
}
This will not stop you from separating the closing </tag>
from a <tag>
, but it will stop you from breaking a tag in the middle.
Upvotes: 0
Reputation: 11782
You won't be able to find if you've broken your html but cutting the string reliably with the method you're trying. How would you detect cases like this?
Hello good morning<span class='whatever'><div class='somethingelse'>blah</div>
You're going to need to employ the use of a HTML Parser. Find where you want to cut the string and check that against your HTML Parser to see if you're inside an unclosed element.
Upvotes: 1