note 82056 added to function.substr-replace
| From: | jaimthorn at yahoo dot com | Date: | Wed, 26 Mar 2008 06:53:22 +0000 |
| Subject: | note 82056 added to function.substr-replace | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-137587@lists.php.net to get a copy of this message | ||
I recently needed a routine that would remove the characters in one string from another, like the
regex
<?php
$result = preg_replace("/[$chars]/", "", $string);
?>
and I needed it to be fast, and accept pretty much all input. The regex above won't work when
strlen($chars) == 0. I came up with this, admittedly pretty horrible-looking code, that is quite
fast:
<?php
function RemoveChars($string, $chars)
{
return isset($chars{0}) ? str_replace($chars{0}, "", strtr($string, $chars,
str_pad($chars{0}, strlen($chars), $chars{0}))) : $string;
}
?>
According to my own measurements, the regex in ONLY faster for when strlen($chars) == 1; for longer
strings, my routine is faster. What does it do? Let's say you want to remove the period, the
comma and the exclamation mark from a string, like so:
$result = RemoveChars("Isn't this, like, totally neat..!?", ".?!");
The str_pad function creates a string equal in length to the string that contains the character to
be removed, but consisting only of the first character of that string:
The input is ".,!"
The output is "..."
The strtr function translates all characters in the string-to-be-processed ("Isn't
this...") that also occur in the input (".,!") to the characters in the same position
in the output ("..."). In other words:
Isn't this, like, totally neat..!?
becomes
Isn't this. like. totally neat....
Finally, the first character from the input (".,!") which happens to be, again, the
period, is removed from that string by the str_replace call:
Isn't this like totally neat?
The function needs to check is $chars has at least one character, or else the str_pad function will
fail. If it's empty, then the unprocessed string is returned.
----
Server IP: 195.184.64.198
Probable Submitter: 24.132.180.10
----
Manual Page -- http://www.php.net/manual/en/function.substr-replace.php
Edit -- https://master.php.net/note/edit/82056
Del: integrated -- https://master.php.net/note/delete/82056/integrated
Del: useless -- https://master.php.net/note/delete/82056/useless
Del: bad code -- https://master.php.net/note/delete/82056/bad+code
Del: spam -- https://master.php.net/note/delete/82056/spam
Del: non-english -- https://master.php.net/note/delete/82056/non-english
Del: in docs -- https://master.php.net/note/delete/82056/in+docs
Del: other reasons-- https://master.php.net/note/delete/82056
Reject -- https://master.php.net/note/reject/82056
Search -- https://master.php.net/manage/user-notes.php