Example 1: php strip out special characters
function clean($string) {
$string = str_replace(' ', '-', $string);
return preg_replace('/[^A-Za-z0-9\-]/', '', $string);
}
Example 2: Remove Special Character in PHP
phpCopy<?php
function RemoveSpecialChar($str)
{
$res = preg_replace('/[0-9\@\.\;\" "]+/', '', $str);
return $res;
}
$str = "My name is hello and email [email protected];";
$str1 = RemoveSpecialChar($str);
echo "My UpdatedString: ", $str1;
?>
Example 3: remove invalid characters from a string laravel
function hyphenize($string) {
$dict = array(
"I'm" => "I am",
"thier" => "their",
);
return strtolower(
preg_replace(
array( '#[\\s-]+#', '#[^A-Za-z0-9. -]+#' ),
array( '-', '' ),
cleanString(
str_replace(
array_keys($dict),
array_values($dict),
urldecode($string)
)
)
)
);
}
function cleanString($text) {
$utf8 = array(
'/[áàâãªä]/u' => 'a',
'/[ÁÀÂÃÄ]/u' => 'A',
'/[ÍÌÎÏ]/u' => 'I',
'/[íìîï]/u' => 'i',
'/[éèêë]/u' => 'e',
'/[ÉÈÊË]/u' => 'E',
'/[óòôõºö]/u' => 'o',
'/[ÓÒÔÕÖ]/u' => 'O',
'/[úùûü]/u' => 'u',
'/[ÚÙÛÜ]/u' => 'U',
'/ç/' => 'c',
'/Ç/' => 'C',
'/ñ/' => 'n',
'/Ñ/' => 'N',
'/–/' => '-',
'/[’‘‹›‚]/u' => ' ',
'/[“”«»„]/u' => ' ',
'/ /' => ' ',
);
return preg_replace(array_keys($utf8), array_values($utf8), $text);
}
Example 4: Remove Special Character in PHP
phpCopy<?php
$str = "geeks";
$str = ltrim($str, 'g');
echo $str;
?>
Example 5: php regex replace to remove special characters and accented
$unwanted_array = array( 'Š'=>'S', 'š'=>'s', 'Ž'=>'Z', 'ž'=>'z', 'À'=>'A', 'Á'=>'A', 'Â'=>'A', 'Ã'=>'A', 'Ä'=>'A', 'Å'=>'A', 'Æ'=>'A', 'Ç'=>'C', 'È'=>'E', 'É'=>'E',
'Ê'=>'E', 'Ë'=>'E', 'Ì'=>'I', 'Í'=>'I', 'Î'=>'I', 'Ï'=>'I', 'Ñ'=>'N', 'Ò'=>'O', 'Ó'=>'O', 'Ô'=>'O', 'Õ'=>'O', 'Ö'=>'O', 'Ø'=>'O', 'Ù'=>'U',
'Ú'=>'U', 'Û'=>'U', 'Ü'=>'U', 'Ý'=>'Y', 'Þ'=>'B', 'ß'=>'Ss', 'à'=>'a', 'á'=>'a', 'â'=>'a', 'ã'=>'a', 'ä'=>'a', 'å'=>'a', 'æ'=>'a', 'ç'=>'c',
'è'=>'e', 'é'=>'e', 'ê'=>'e', 'ë'=>'e', 'ì'=>'i', 'í'=>'i', 'î'=>'i', 'ï'=>'i', 'ð'=>'o', 'ñ'=>'n', 'ò'=>'o', 'ó'=>'o', 'ô'=>'o', 'õ'=>'o',
'ö'=>'o', 'ø'=>'o', 'ù'=>'u', 'ú'=>'u', 'û'=>'u', 'ý'=>'y', 'þ'=>'b', 'ÿ'=>'y' );
$str = strtr( $str, $unwanted_array );
Example 6: Remove Special Character in PHP
phpCopy<?php
$string = "DelftStack is a best platform.....";
echo "Output: " . rtrim($string, ".");
?>