'PhP regex, remove white spaces and all special characters from string [duplicate]

I have a variable $name which can sometimes contain spaces and special characters like '%' '&' etc.how can I remove all of those using regex or in any other way?

 */
public function handle()
{
    $urls = Business::pluck('ical');
    $names = Business::pluck('name');
    foreach ($urls as $url) {
        foreach ($names as $name) {
            $test= explode("\n", $name);
            dd($test);
        $response = Curl::to($url)
            ->download('ical/'.$name.'.ics');
    }   


Solution 1:[1]

Use the preg_replace() function of PHP.

$name = preg_replace('/[^\w\d]+/', '', $name);

The regex /[^\w\d]+/ matches all white space and special characters.

https://www.tinywebhut.com/regex/2

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Andreas