Re: strpos() before str_replace()? Or, maybe strtr()? [message #184925 is a reply to message #184923] |
Sun, 16 February 2014 16:23 |
Thomas 'PointedEars'
Messages: 701 Registered: October 2010
Karma:
|
Senior Member |
|
|
Christoph Michael Becker wrote:
> Jason C wrote:
>> 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);
>> }
>>
>> […]
>> Or, would strtr() be faster? I've never actually used this function in
>> practice; I think it's a slow function, but have never tested it, and
>> don't remember where I read that:
>>
>> $firstname = strtr($firstname, $userArr);
>> $lastname = strtr($lastname, $userArr);
>>
>> Any other suggestions on what might be the fastest option?
>
> Having the fastest option is surely less important than having a correct
> solution, and there is an important semantic difference between
> str_replace() and strtr(). Consider the following snippet:
>
> $array = array('some' => 'any', 'anything' => 'nothing');
> $name = 'something';
>
> $keys = array_keys($array);
> $values = array_values($array);
> var_dump(str_replace($keys, $values, $name));
>
> var_dump(strtr($name, $array));
>
> This will output:
>
> string(7) "nothing"
> string(8) "anything"
There *is* a semantic difference. He did not call str_replace() with array
parameters, though, nor did he suggest so.
PointedEars
--
Sometimes, what you learn is wrong. If those wrong ideas are close to the
root of the knowledge tree you build on a particular subject, pruning the
bad branches can sometimes cause the whole tree to collapse.
-- Mike Duffy in cljs, <news:Xns9FB6521286DB8invalidcom(at)94(dot)75(dot)214(dot)39>
|
|
|