note 83145 deleted from function.str-replace by felipe
| From: | felipe@php.net | Date: | Sat, 21 Jun 2008 14:05:24 +0000 |
| Subject: | note 83145 deleted from function.str-replace by felipe | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-140638@lists.php.net to get a copy of this message | ||
Note Submitter: John
----
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");