Limit characters in a string

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Jim_Bo
Forum Contributor
Posts: 390
Joined: Sat Oct 02, 2004 3:04 pm

Limit characters in a string

Post by Jim_Bo »

Hi,

Im trying to create a function to limit the characters within a string, then keep going untill it finds the first space in the string and echo the results.

Code: Select all

function LimitString() {
	$limit=14;
	$value = substr($value, $limit, 1);
if($value != " "){
	while($value != " "){
		$i = 1;
		$limit = $limit + $i;
		$value = substr($value, $limit, 1);
 }
}
	$value = substr($value, 0, $limit);
	return $value; 
}
Thats what I have so far, but makes the browser output page can not be displayed.

Am I on the right track?


Thanks
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Post by superdezign »

You set the value of $value a hell of a lot of times.

What you're attempting to return is multiple characters in a string of only one.


Maybe, to simplify, have your function take the string as a parameter.. maybe $sString, then traverse THAT string using $value = substr($sString, $limit, 1).

Return substr($sString, 0, $limit), and it should work.
Jim_Bo
Forum Contributor
Posts: 390
Joined: Sat Oct 02, 2004 3:04 pm

Post by Jim_Bo »

Hi,

Do u mean something like:

Code: Select all

function LimitString() {
	$limit = 14;
	$value = substr($sString, $limit, 1);
if($value != " "){
	while($value != " "){
		$i = 1;
		$limit = $limit + $i;
		$value = substr($sString, $limit, 1);
 }
}
	return substr($sString, 0, $limit);
}

That stills returns "Page can not be displayed"


Thanks
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Post by superdezign »

take the string as a parameter
More like

Code: Select all

function LimitString($sString) {
Post Reply