View Full Version : Cuting n' managing Strings

12-18-2003, 08:12 PM
Hi there,
I have this Variable, $Texto, is a string to large actually is the text of an articla from a magazine column, and I dont want to show all the text in my Articles Index, so I want to cut it, lets say at the 100th character; does any one know how I can do it, some like de JS's split() function. And I also need to find the way to replace inside a string, something like JS's replace().
Any help will be useful, thnx.

12-18-2003, 08:24 PM
I wrote a function for someone long ago to essentially what you are asking. You can read about it in this thread


12-19-2003, 10:51 PM
Teach a man to fish...

When you have a question like that, ALWAYS check the language documentation first. It'll save ya lots of time waiting on bozos like us to respond!


PHP has several built-in functions for just this. They are:

substr(string,start[,length ])


There is also the entire "ereg" set of functions, used for complicated replaces.

Examples of what you're doing:

$Texto = "This is a whole bunch of text, blah blah, an article....";
$portion = substr($Texto,0,15); // pull the first 16 characters


$haystack = "I went to the store and bought a turtle.";
$needle = "turtle";
$replace_with = "monkey";
$new_string = str_replace($needle,$replace_with,$haystack);
print $new_string; // Prints: I went to the store and bought a monkey.

Hope that helps!

12-23-2003, 07:58 PM
Thnx for the replays guys, but now I have this problem:
I Have de same old big string $TEXTO that has several <br /> after I nl2br it, but the thing now is that I just do not replace the repeated <br /> with what I want. I wan't to replace two br tags, a newline and an other two br tags for some character like *.
I don't know why nl2br() does not remove the newlines from the string, and I don't know why this replace does not work at all.

$portionTEXTO= nl2br($TEXTO);
$BRs = "<br />";
$VariosBRs = $BRs.$BRs."\n".$BRs.$BRs;
$PuntosYAparte = ".".$BRs;
$MarcaPropia = "|*";
$Nada=" ";
$portionTEXTO = str_replace($VariosBRs, $MarcaPropia, $portionTEXTO);//this string_replace is the problem does not match the $VariosBRs
$portionTEXTO = str_replace($BRs, $Nada, $portionTEXTO);
$portionTEXTO = str_replace($MarcaPropia, $PuntosYAparte, $portionTEXTO);

I guess the problem is with some kind of Regular Expretion or some thing...
Any hel will be usefull