Shorten text with preg_replace()


633
If you want to shorten your description text while removing any unwanted special characters, there is an efficient way to do it.
This is advantageous in product_listing.php, for example.

The shortened text is not cut off in the middle of the word, but only afterwards.

Check whether the following section is defined in the sql query:

SUBSTRING_INDEX(pd.products_description, ' ', '10') as products_description,

Change this so that the base query looks like this:

pd.products_description,

Then insert this code sequence:

    $originaldescriptionstring = $variable['products_description']; 
    $outputdescriptionstring = preg_replace ('/<[^>]*>/', '', $originaldescriptionstring);
    $dsc_string	= $outputdescriptionstring;
    $dsc_length	= '45';
    $dsc_output	= preg_replace( '/[^ ]*$/', '', substr( $dsc_string, 0, $dsc_length ) ) . ' ...';

At the point of the issued product description:
Example:

 . $variable['products_description'] . 

replace with the following:

 . $dsc_output . 

or

<?php echo $variable['products_description'];?>

replace with the following:

<?php echo $dsc_output;?>

The text is shortened to 45 letters, all special characters are removed and the last word is not cut off in the middle.


Information(1)
General information
 Lazy Loading
Post counter
Current information status:
Categories: 8
Posts: 104
Support pages: 51
Downloads for members: 104
Download counter: 646