note 22651 added to function.substr
| From: | chris@php.net | Date: | Wed, 26 Jun 2002 02:57:48 +0000 |
| Subject: | note 22651 added to function.substr | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-32205@lists.php.net to get a copy of this message | ||
This function will cut strings at the first space before a specified number of characters, and not
in the middle of words or tags.
I'm pretty new at php, so if this is well...crappy and/or inefficient, sorry :(
/* $m is the position from
where the function starts working well -
backwards */
function chop_string($string,$m)
{
$string .= " ";
while($m>0)
{
if($string{$m} == " ")
{
break;
}
else
{
$m--;
}
}
$cut_string = substr($string, 0, $m);
$occur_num = substr_count($cut_string,"<");
if($occur_num > 0)
{
$b = 0;
while(($occur_num > $b) && ($m>0))
{
if(ereg("(<(.*)>)",$cut_string))
{
$b++;
}
else
{
$m--;
$cut_string = substr($cut_string, 0, $m);
$occur_num = substr_count($cut_string,"<");
}
}
}
return substr($cut_string, 0, $m);
}
$string = "This a string containing at least 25 characters";
echo chop_string($string,"25");
Chris
--
http://www.php.net/manual/en/function.substr.php
http://master.php.net/manage/user-notes.php?action=edit+22651
http://master.php.net/manage/user-notes.php?action=delete+22651
http://master.php.net/manage/user-notes.php?action=reject+22651