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
$mainstr = "<h2>Welcome to <b>PHPWorld</b></h2>";
echo "Text before remove: \n" . $mainstr;
echo "\n\nText after remove: \n" .
str_ireplace(array('<b>', '</b>', '<h2>', '</h2>'), '',
htmlspecialchars($mainstr));
?>
Example 5: Remove Special Character in PHP
phpCopy<?php
$str = "@@HelloWorld";
$str1 = substr($str, 1);
echo $str1 . "\n\n";
$str1 = substr($str, 2);
echo $str1;
?>
Example 6: Remove Special Character in PHP
phpCopy<?php
$strTemplate = "My name is :name, not :name2.";
$strParams = [
':name' => 'Dave',
'Dave' => ':name2 or :password',
':name2' => 'Steve',
':pass' => '7hf2348', ];
echo "\n" . strtr($strTemplate, $strParams) . "\n";
echo "\n" . str_replace(array_keys($strParams), array_values($strParams), $strTemplate) . "\n";
?>