...

View Full Version : trim () alternative function ?



lol
09-17-2003, 11:31 PM
Hi!
can someone help me make an alternative trim() function.
the reason I need it, because trim($text, ","); works only on PHP v4.1.0 and higher.

so, I was trying use preg_replace(), but since I s@x with REGEX, it didnt work properly.
here is a working example:

function trim_alt($text, $what) {
return preg_replace("/^($what)?(.*)($what)?$/ms", "\\2", $text);
}
$text = ".I want strip all '.' \n from this text.".
"But it doesnt work.";
echo "1- ".$text."<br>2- ".trim($text, ".")."<br>3- ".trim_alt($text, ".");
printed number 2 and number 3 should be identical, but 3 doesnt strip dot from the end...what did I miss?
or maybe there is a better way to do so?
thank in advance.

maltrecho
09-18-2003, 02:41 AM
I don't understand well the question but if what you want is to strip the dots you can try:


$text = ".I want strip all '.' \n from this text.".
"But it doesnt work.";

echo str_replace(".","",$text);


trim() is usually used to eliminate extra spaces.

lol
09-18-2003, 04:17 AM
yes, trim() without second parameter will strip spaces at the both ends. And trim($string, "."); will strip dots from both ends, but in PHP older then 4.1.0 this second parameter (in my example its ".") is not implimented. Because of that, I'm looking for a "custom" function that would be alternative to trim(), that would do exactly what trim() does, but would work with any PHP version.
In your example str_replace() will strip ALL dots from the sting, but all I need is strip dots from the both ends only.

P.S. just realised, that in my first post example sais "strip all '.' from the string", but it should be "strip '.' from both ends of the string", sorry for the confusion, and thanks for the try ;)

maltrecho
09-18-2003, 04:34 AM
<?php

$text = ". bla . bla . bla .";

$expression = "/(^[\"|.]|[\"|.]$)/";

$newtext = preg_replace($expression, '', $text);

echo $newtext;

?>


But the dots must be in the very first place of the expression ($text) or in the very last.

found in php.net (http://es2.php.net/manual/en/function.preg-replace.php)

V@no.
09-18-2003, 04:53 AM
So, the function that u are looking for would looks like this:

function trim_alt($text, $what) {
return preg_replace("/(^[$what]*|[$what]*$)/", "", $text);
}



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum