Page 1 of 1

Trimming a string that exceeds a length

Posted: Tue Feb 14, 2006 5:13 pm
by kyoru

Code: Select all

$Length = 5;
$Str = 'asqvasyhafveryf';

if(strlen($Str) > $Length){
    preg_match('/[a-zA-Z0-9]{0,'.$Length.'}/', $Str, $M);
    $Output = $M . '...';
}
I tried using this code, but it did not work, so i tried figuring out what it really does. I took out '. & .', what do the slashes mean? and when i print the output it prints out the word "Array", so im guessing $M is the output variable. Any help would be great thanks :D

Posted: Tue Feb 14, 2006 5:25 pm
by feyd
check out the documentation on the function: preg_match()
An explaination of what everything means can be found through the stickies in the Regex board.
var_export(), print_r() and var_dump() may be of interest too.

Posted: Tue Feb 14, 2006 5:29 pm
by josh
substr would be good for this

Posted: Tue Feb 14, 2006 8:03 pm
by khaki_monster
hi!

this is one of my functions particularly to trim exceeding lenght of a string.
hope this may help. :)

Code: Select all

function charslen($str){
        // 42 characters is supposed to return if TRUE
	if(strlen($str) > 42){
		$chunk = trim(substr($str, 1, 42));
		$str = $chunk.'...';
		return($str);
	}else{
		return($str);
	}	
}

/*
example:

$var = 'sdfsd sdf sdfsdfsdfsdfsdfsdfs sdfsdf sdf'';

echo charslen($var);

*/
cheerz!

Posted: Wed Feb 15, 2006 12:43 am
by kyoru
thanks alot guys, preg_match was a big headache for me but substr was perfect!

Posted: Wed Feb 15, 2006 5:44 am
by khaki_monster
glad we've help yah... :) i dont like regex but basically its important also to learn some regex.

cheerz!