Jump to content

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

 

 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.