Jump to content

[SOLVED] str_replace no work with arrays


koolego

Recommended Posts

 

Does anyone understand how to use str_replace or preg_replace to remove items from arrays? The below codes works to remove  '  from the text

 

 

<?php
$b_result = "how do I remove all the ' from my array's";

  $b_result = str_replace(" ' ", " ", $b_result);
//$b_result = preg_replace ("|(')|", " ", $b_result);

echo "<pre>";
print_r ($b_result);
?>

 

However when using an array as shown below it fails

 

<?php
    [5] => Array
        (
            [0] => 6.
            [1] => 8.8
            [2] => Schindler's List
            [3] =>  (1993)
        )

    [6] => Array
        (
            [0] => 7.
            [1] => 8.8
            [2] => One Flew Over the Cuckoo's Nest
            [3] =>  (1975)
        )
?>

 

Lots of documentation around how to do the first but not when it comes to arrays.

Any help would be very welcome.

 

 

Link to comment
https://forums.phpfreaks.com/topic/105739-solved-str_replace-no-work-with-arrays/
Share on other sites

use a foreach loop

ie

 

(untested)

<?php
#$b_result = "how do I remove all the ' from my array's";
$array=array("5" => array("6.","8.8","Schindler's List","(1993)"));

foreach($array as $MK => $item)
{
foreach($item as $K => $V)
{
	$array[$MK][$K] = str_replace("'", "", $V);
}
}

echo "<pre>";
print_r ($b_result);
?>

Or you can use array_map()

<?php
function no_quotes($str) {
    return(str_replace("'",'',$str));
}
$array=array("5" => array("6.","8.8","Schindler's List","(1993)"));
foreach ($array as $mk => $suba)
      $array[$mk] = array_map('no_quotes',$suba);
echo '<pre>' . print_r($array,true) . '</pre>';
?>

 

Ken

 

Hey Guys,

 

This is great so a big thank you,

 

Phpfreaks looks like a great place to hang out not just to have questions answered but to learn how to approach a coding problem or saturation that people post.

 

I have enjoyed my first visit very much

 

;D ;D ;D

 

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.