用于连字动态网址的下划线

I have the following existing .htaccess in place

RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\.example\.com
RewriteRule (.*) http://www.example.com/$1 [R=301,L] 
RewriteRule home index.php [L]
RewriteRule ^([^/]*)/$ /index.php?TopicID=$1 [L]
RewriteRule ^([^/]*)/([^/]*)/$ /index.php?RollID=$1&FrameID=$2 [L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule (.*) $1.php [L]
RedirectMatch 301 /cache(.*) //$1
ErrorDocument 404 http://www.example.com/error.php

I have many dynamically generated URLs which are being rewritten to this

www.example.com/abc_def_ghi/ OR www.example.com/abc_def_ghi/abc_def_ghi/

and i'd like to end up with this

www.example.com/abc-def-ghi/ OR www.example.com/abc-def-ghi/abc-def-ghi/

I've tried adding this to the end of my .htaccess

Options +FollowSymLinks
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} !.(html|php)($|?) [NC]
RewriteRule ^([^_]*)_+(.*)$ $1-$2 [E=underscores:Yes,N]
RewriteCond %{ENV:underscores} ^Yes$
RewriteRule (.*) http://%{HTTP_HOST}/$1 [R=301,L]

but i'm getting a 500 error. Can anyone help?

Rearrange your rules like this:

ErrorDocument 404 http://www.example.com/error.php
RewriteEngine on

RewriteRule ^cache(.*) /$1 [L,R=301]

RewriteCond %{HTTP_HOST} !^www\.example\.com
RewriteRule (.*) http://www.example.com/$1 [R=301,L] 

# if there is only one underscore then repalce it by - and redirect
RewriteRule ^([^_]*)_([^_]*)$ /$1-$2 [L,R=302]

# if there are more than one underscores then "repeatedly" repalce it by - and set env var
RewriteRule ^([^_]*)_([^_]*)_(.*) $1-$2-$3 [E=USCORE:1]

# if USCORE env var is set and there is no underscore left then redirect
RewriteCond %{ENV:REDIRECT_USCORE} =1
RewriteRule ^([^_]+)$ /$1 [L,R=302]

RewriteRule home index.php [L]

RewriteCond %{REQUEST_FILENAME} -d
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]

RewriteRule ^([^/]+)/?$ /index.php?TopicID=$1 [L,QSA]

RewriteRule ^([^/]+)/([^/]+)/?$ /index.php?RollID=$1&FrameID=$2 [L,QSA]

RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule (.*) $1.php [L]