Re: str_replace & assign to a var? [message #182760 is a reply to message #182758] |
Thu, 05 September 2013 08:48 |
Curtis Dyer
Messages: 34 Registered: January 2011
Karma:
|
Member |
|
|
"J.O. Aho" <user(at)example(dot)net> wrote:
> On 04/09/13 19:29, Twayne wrote:
>> Hi Guys & Gals,
>>
>> If this is a dumb question I apologize but I'm stuck. Yes, I'm
>> essentially a newbie to many things yet in PHP.
>>
>> I have the following canned code:
>> ------------
>> $arr = array("blue","red","green","yellow");
>> print_r(str_replace("red","pink",$arr,$i));
>> echo "<br>" . "Replacements: $i";
>> -----------
>>
>> All I want to do is change "red" to "pink" IN the array or a
>> new array. How do I do that?
>>
>>
>> In other words, I want to change the original array to have
>> "pink" in it instead of "red".
Have you checked the PHP documentation? This is clearly explained:
<http://php.net/str_replace>.
<snip>
> Here is an example how to make it neatly and this can be made
> quite dynamic by chancing the function to use for remapping the
> cell content:
>
> <?php
>
> function filterNumbers($str) {
> return str_replace('-', '', $str);
> }
>
> $oldArray=array('1234-1234', '2345-2345', 'ABCD.FGHI',
> '3456.3456', '-0987-0987');
>
> $newArray=array_map('filterNumbers', $oldArray);
>
> var_dump($newArray);
>
> ?>
>
> The filterNumbers do the actual work (you can make it a lot more
> advanced, depending on your needs).
In this case, however, it seems unnecessary. The `str_replace'
function will already return the altered array when the `subject'
parameter is an array. So, in the OP's code snippet above, we need
to change the `str_replace' line:
<?php
$i = 0;
/* ... */
$arr = str_replace('red', 'pink', $arr, $i);
print_r($arr);
?>
<snip>
--
Curtis Dyer
<?$x='<?$x=%c%s%c;printf($x,39,$x,39);?>';printf($x,39,$x,39);?>
|
|
|