Ad

How To Remove Unwanted Characters With Regex In Php

- 1 answer

I'm trying to remove all unusual characters from a string with php (codeigniter 3) but I got this error message preg_replace(): Unknown modifier '0'. what am I doing wrong?

input: bang bang..Â

expected output: bang bang..

here's my code:

/application/libraries/Common.php

class Common
{
    public function __construct()
    {
        $this->ci = &get_instance();
    }

    public function remove_weird_characters($str)
    {
        $whitelist = "!\"#$%&'()*+,-./0123456789:;<=>[email protected][\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
        return preg_replace("/[^{$whitelist}]+/", "", $str);
    }
}

/application/modules/test/controllers/Test.php

class Test extends MY_Controller
{
    public function test1()
    {
        print_r($this->common->remove_weird_characters("bang bang..Â"));
    }
}
Ad

Answer

You could try this

echo preg_replace('/[^[:ascii:]]/', '', $str);

Remove all characters not contained in ascii code.

---Update---

I've fixed your code and it works now!

$whitelist = "!\"#$%&'()*+,-.\/0123456789:;<=>[email protected][\]^_`abcdefghijklmnopqrstuvwxyz{|}~ ";
echo preg_replace("/[^{$whitelist}]/", "", $str);
Ad
source: stackoverflow.com
Ad