basically i want to remove unwanted characters from string - i have a list of valid characters in a regex or map ( or whatever that is )
基本上我想从字符串中删除不需要的字符 - 我有一个正则表达式或地图中的有效字符列表(或任何其他)
$permitted_uri_chars = ' ) ( ( ) a-z 0-9~%.+:_\- δ ο κ ι μ ή χ ό ν';
right now i'm using this code which seems slow and messy and above all i have to write every single character ( i cant do a-z 0-9 )
现在我正在使用这个看似缓慢而凌乱的代码,最重要的是我必须编写每一个字符(我不能做a-z 0-9)
$string = "this is a test";
$permitted_uri_chars = ' ) ( ( ) a b c d e z 0 1 2 3 4 9 _ - δ ο κ ι μ ή χ ό ν';
$permitted_uri_chars = explode(' ' , $permitted_uri_chars );
$unwanted = array();
for($i = 0 ; $i < strlen($string) ; $i++)
{
if(!in_array($string[$i] , $permitted_uri_chars ))
$unwanted[] = $string[$i] ;
}
$string = str_replace($unwanted, '-' , $string);
echo $string;
2 个解决方案
#1
1
preg_replace()
is probably the best tool for the job:
preg_replace()可能是这项工作的最佳工具:
$string = preg_replace('/[^\da-z~%\.\+:_\-δοκιμήχόν]/i', '', $string);
#2
1
Use preg_replace()
here instead, using a negated character class.
在这里使用preg_replace(),使用否定的字符类。
Note: Not clear if parentheses are permitted, but you can remove them if you need to. I included them since you have multiple in $permitted_uri_chars
.
注意:不清楚是否允许使用括号,但如果需要,可以删除它们。我把它们包括在内,因为你在$ allowed_uri_chars中有多个。
$string = preg_replace('/[^a-z0-9δοκιμήχόν_()%~.:+-]/i', '', $string);
#1
1
preg_replace()
is probably the best tool for the job:
preg_replace()可能是这项工作的最佳工具:
$string = preg_replace('/[^\da-z~%\.\+:_\-δοκιμήχόν]/i', '', $string);
#2
1
Use preg_replace()
here instead, using a negated character class.
在这里使用preg_replace(),使用否定的字符类。
Note: Not clear if parentheses are permitted, but you can remove them if you need to. I included them since you have multiple in $permitted_uri_chars
.
注意:不清楚是否允许使用括号,但如果需要,可以删除它们。我把它们包括在内,因为你在$ allowed_uri_chars中有多个。
$string = preg_replace('/[^a-z0-9δοκιμήχόν_()%~.:+-]/i', '', $string);