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.
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
)
?>
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With