note 83144 deleted from function.str-replace by nlopess

From: Date: Sun, 25 May 2008 08:56:57 +0000
Subject: note 83144 deleted from function.str-replace by nlopess
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-139723@lists.php.net to get a copy of this message
Note Submitter: Anonymous ---- I see this a lot: "I wrote a simple (... yeah, right ...) function to replace two of this (spaces, newlines, tabs, you name it) with just one of them!", followed by a function that works 90% of the time. People, PEOPLE, abstract it out. You want: $this = "This*is**your*****string"; to become: $this = "This*is*your*string"; what you need is a function like smash($mystring [, $somechar]); and if we leave off the second argument it fills in with, oh, I dunno, a space char. First, the test (a la SimpleTest): class Test_Smash_Function extends UnitTestCase { function test_smash_replaces_more_than_one_with_one() { $test_string = "This%%%%is%%%%%%the%test%%string"; $result = smash($test_string, '%'); $this -> assertEqual($result, "This%is%the%test%string"; } } We now have a failing test. Horray! Now, the function: function smash($inspect_string, $char=" "); { return(preg_replace("/[$char]{2,}/", $char, $inspect_string)); } It passes. You're done! // more than one space becomes just one space: $clean_string = smash($my_intermediate_dirty_string); // more than one tab becomes just one tab: $clean_string = smash($my_intermediate_dirty_string, "\t");

« previous php.notes (#139723) next »