چگونه special character ها را از نوشته با PHP حذف کنیم ؟

چگونه special character ها را از نوشته با PHP حذف کنیم ؟ – با کمک توابع str_replace و str_ireplace و preg_replace می توانیم هر نوع کاراکتری را از جمله special character ها را حذف کنیم .
روش 1 : استفاده از تابع str_replace
نکته این تابع case sensitive است .
Syntax :
str_replace( $searchVal, $replaceVal, $subjectVal, $count )
مثال :
<?php
// PHP program to Remove
// Special Character From String
// Function to remove the spacial
function RemoveSpecialChar($str) {
// Using str_replace() function
// to replace the word
$res = str_replace( array( '\'', '"',
',' , ';', '<', '>' ), ' ', $str);
// Returning the result
return $res;
}
// Given string
$str = "Example,to remove<the>Special'Char;";
// Function calling
$str1 = RemoveSpecialChar($str);
// Printing the result
echo $str1;
?>
خروجی
Example to remove the Special Char
روش 2 : استفاده از تابع str_ireplace
این تابع بر خلاف str_replace به حروف بزرگ و کوچک حساس نیست .
Syntax:
str_ireplace( $searchVal, $replaceVal, $subjectVal, $count )
مثال :
<?php
// PHP program to Remove
// Special Character From String
// Function to remove the spacial
function RemoveSpecialChar($str){
// Using str_ireplace() function
// to replace the word
$res = str_ireplace( array( '\'', '"',
',' , ';', '<', '>' ), ' ', $str);
// returning the result
return $res;
}
// Given string
$str = "Example,to remove<the>Special'Char;";
// Function calling
$str1 = RemoveSpecialChar($str);
// Printing the result
echo $str1;
?>
خروجی
Example to remove the Special Char
روش 3 : استفاده از تابع preg_replace
این تابع نیازمند استفاده از regex است .
Syntax :
preg_replace( $pattern, $replacement, $subject, $limit, $count )
مثال :
<?php
// PHP program to Remove
// Special Character From String
// Function to remove the spacial
function RemoveSpecialChar($str){
// Using preg_replace() function
// to replace the word
$res = preg_replace('/[^a-zA-Z0-9_ -]/s',' ',$str);
// Returning the result
return $res;
}
// Given string
$str = "Example,to remove<the>Special'Char;";
// Function calling
$str1 = RemoveSpecialChar($str);
// Printing the result
echo $str1;
?>
خروجی
Example to remove the Special Char
ارسال نظر