note 83145 added to function.str-replace

From: Date: Mon, 12 May 2008 22:22:52 +0000
Subject: note 83145 added to function.str-replace
Groups: php.notes 
Request: Send a blank email to php-notes+get-139318@lists.php.net to get a copy of this message
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"); ---- Server IP: 64.71.164.2 Probable Submitter: 128.171.188.52 ---- Manual Page -- http://www.php.net/manual/en/function.str-replace.php Edit -- https://master.php.net/note/edit/83145 Del: integrated -- https://master.php.net/note/delete/83145/integrated Del: useless -- https://master.php.net/note/delete/83145/useless Del: bad code -- https://master.php.net/note/delete/83145/bad+code Del: spam -- https://master.php.net/note/delete/83145/spam Del: non-english -- https://master.php.net/note/delete/83145/non-english Del: in docs -- https://master.php.net/note/delete/83145/in+docs Del: other reasons-- https://master.php.net/note/delete/83145 Reject -- https://master.php.net/note/reject/83145 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#139318) next »