DISPLAYING THE FIRST X CHARACTERS IN A WYSIWYG FIELD ON A LISTING PAGE - May 8th, 2011


User Deborah had this challenge.

She said:
I am (trying to use) a cutText function to limit the number of characters in a WYSIWYG field. Because the WYSIWYG
content automatically generates a closing </p> tag, I am unable to append a dot leader and "more" link such as this at
the end of the snipped text:



<p>WYSIWYG content blah, blah, blah ... <a href="<?php echo $record['_link']; ?>”>Read More</a>></p>



The first step in using cutText is to define the function in the head section of your viewer.



<?php function cutText($string, $setlength) {
$length = $setlength;
if(
$length<strlen($string)){
while ((
$string{$length} != " ") AND ($length > 0)) {
$length--;}
if (
$length == 0) return substr($string, 0, $setlength);
else return
substr($string, 0, $length);}
else return
$string; }
?>



But when Deborah tried to implement the cutText function and preg_replace to accomplish her goal, it resulted in this
code:



<?php echo cutText($record['my_field']= preg_replace("|</p>\s*$|i", "...</p>", $record['my_field'] ), 90); ?>



but that did not work consistently.

Chris Waddell from Interactive Tools said:

Using the cutText() function (in this way) is (sometimes) stripping off the </p>. With no </p>, the preg_replace()
can't find the right place to add the ...

For consistency, I'd recommend stripping the </p> off first, then calling cutText(), then adding your read more link,
and finally replacing the </p> using the following code in the foreach loop:



<?php
$html = preg_replace("|</p>\s*$|i", "", $record['my_field'] );
$html = cutText($html, 90);
$html = $html . "...</p>";
echo
$html;
?>



The materials on this web site have been created for use with CMS Builder content management software. CMS Builder software is published and licensed for use by InteractiveTools.com. Please contact Interactive Tools for information on the downloading of the software or the purchasing of licenses.


Terms of Service