in reply to Re^4: How to use \W in Regular Expression?
in thread How to use \W in Regular Expression?

It'll ignore everything it doesn't match. You don't have to do anything.

If $query contains a literal text to match:

$str =~ s/\Q$query\E/<em>$query<\/em>/ig;

If $query contains a regex pattern:

$str =~ s/($query)/<em>$1<\/em>/ig;