my $num_ent_chars = "()"; # add other characters as needed, but ^ - [ ] are special $data =~ s/([$num_ent_chars])/sprintf("&#x%4x;",ord($1))/ge; #### perl -le '$_="me [ and ] you ^ and - him"; $c="][^-"; s/[$c]/xxx/g; print'