Swapnil Chaudhari
Swapnil Chaudhari

Reputation: 75

How to remove any special character from php array?

How to remove any special character from php array?

I have array like:

$temp = array (".com",".in",".au",".cz");

I want result as:

$temp = array ("com","in","au","cz");

I got result by this way:

$temp = explode(",",str_replace(".","",implode(",",$temp)));

But is there any php array function with we can directly remove any character from all values of array? I tried and found only spaces can be removed with trim() but not for any character.

Upvotes: 5

Views: 24701

Answers (4)

Eaten by a Grue
Eaten by a Grue

Reputation: 22931

Actually trim() can trim any character(s) you wish if you provide the 2nd argument (character mask). As it's name implies, this will only remove characters from the beginning and end of the string. In your case ltrim() may be more appropriate.

You can use array_map() and ltrim() together with a third parameter for the character mask like this:

$temp = array_map('ltrim', $temp, array_fill(0, count($temp), '.'));

The third parameter should be an array of arguments matching the length of the array you're processing, which is why I used array_fill() to create it.

Upvotes: 0

Rubin Porwal
Rubin Porwal

Reputation: 3845

As a solution to your problem please execute the following code snippet

    $temp = array (".com",".in",".au",".cz");
    function strip_special_chars($v)
    {
        return str_replace('.','',$v);
    }
    $result[]=array_map('strip_special_chars',$temp);

Upvotes: 0

Saswat
Saswat

Reputation: 12806

I generaly make a function

function make_slug($data)
     {
         $data_slug = trim($data," ");
         $search = array('/','\\',':',';','!','@','#','$','%','^','*','(',')','_','+','=','|','{','}','[',']','"',"'",'<','>',',','?','~','`','&',' ','.');
         $data_slug = str_replace($search, "", $data_slug);
         return $data_slug;
     }

And then call it in this way

$temp = array (".com",".in",".au",".cz");


for($i = 0; $i<count($temp); $i++)
{
    $temp[$i] = make_slug($temp[$i]);
}

print_r($temp);

Each value of $temp will then become free of special characters

See the Demo

Upvotes: 5

John Robertson Nocos
John Robertson Nocos

Reputation: 1485

Use preg_replace function. This will replace anything that isn't a letter, number or space.

SEE DEMO

<?php
$temp = array (".com",".in",".aus",".cz");
$temp = preg_replace("/[^a-zA-Z 0-9]+/", "", $temp );
print_r($temp);

//outputs
Array
(
    [0] =>  com
    [1] =>  in
    [2] =>  aus
    [3] =>  cz
)

?>

Upvotes: 17

Related Questions