Re: strpos() before str_replace()? Or, maybe strtr()? [message #184936 is a reply to message #184932] |
Mon, 17 February 2014 01:44 |
Denis McMahon
Messages: 634 Registered: September 2010
Karma:
|
Senior Member |
|
|
On Sun, 16 Feb 2014 20:53:52 +0000, Ben Bacarisse wrote:
> Ben Bacarisse <ben(dot)usenet(at)bsb(dot)me(dot)uk> writes:
>
>> Norman Peelman <npeelman(at)cfl(dot)rr(dot)com> writes:
>>
>>> On 02/16/2014 04:49 AM, Jason C wrote:
>> <snip>
>>>> foreach ($userArr as $key => $val) {
>>>> if (strpos($firstname, $key) !== false)
>>>> $firstname = str_replace($key, "****", $firstname);
>>>>
>>>> if (strpos($lastname, $key) !== false)
>>>> $lastname = str_replace($key, "****", $lastname);
>>>> }
>>>
>>>
>>> It's slower because you are actually performing the same function
>>> twice on each iteration.
>>
>> Did you try it? In my tests it's faster (37ms vs 66ms). This may be
>> because of the assignment always being done.
>
> I'm pretty sure that it is simply the overhead of str_replace compared
> to that of strpos, and not to do with the assignment.
>
> <snip>
Not sure whether something like this could be faster or not:
foreach ( $userArr as $key => $val ) {
if ( ( $f = strpos( $firstname, $key ) ) !== false )
$firstname = substr( $firstname, 0, $f ) . "****" .
substr( $firstname, $f + strlen( $key ) );
if ( ( $l = strpos( $lastname, $key ) ) !== false )
$lastname = substr( $lastname, 0, $l ) . "****" .
substr( $lastname, $l + strlen( $key ) );
}
As I don't have representative data to test against.
You could use a function:
function replace_stars( $needle, $pos, $haystack ) {
return substr( $haystack, 0, $pos ) . "****" .
substr( $haystack, $pos + strlen( $needle ) );
}
foreach ( $userArr as $key => $val ) {
if ( ( $f = strpos( $firstname, $key ) ) !== false )
$firstname = replace_stars( $key, $f, $firstname );
if ( ( $l = strpos( $lastname, $key ) ) !== false )
$lastname = replace_stars( $key, $f, $lastname );
}
but that would be an extra function call, so I inlined the code instead.
p.s. Yes richard, I used an "=" inside an if test, but the difference is
that I know what I'm doing when I do that, and you don't!
--
Denis McMahon, denismfmcmahon(at)gmail(dot)com
|
|
|