php - removing characters from string if it's not in the regex

211

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 )

 $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;
350

Answer

Solution:

Use here instead, using a negated character class.

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.

$string = preg_replace('/[^a-z0-9δοκιμήχόν_()%~.:+-]/i', '', $string);

People are also looking for solutions to the problem: forms - mail arrive without the file php

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.