Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove any special character from php array?

Tags:

arrays

php

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.

like image 986
Swapnil Chaudhari Avatar asked Dec 01 '22 15:12

Swapnil Chaudhari


2 Answers

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
)

?>
like image 174
John Robertson Avatar answered Dec 09 '22 23:12

John Robertson


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

like image 20
Saswat Avatar answered Dec 09 '22 21:12

Saswat