前导和尾随空白切割+中间空白替换

I have a regex expression for removing leading and trailing white-spaces and also for replacing all others white-spaces in string. But I don't know how to make this work together.

So, my problem is:

string1 " MY FIRST STRING "

I want string1 to appear as:

"my_first_string".

So, I need to remove leading and trailing white-spaces, all other white-spaces needs to be replaced with "_", and the bonus would be to make the string lowercase.

Perform a trim and strtolower before preg_replace:

$str = preg_replace('/\s+/', '_', strtolower(trim($str)));