Ismail H
Ismail H

Reputation: 4489

Matching URI with regex find replace

I'm still learning Regex operations and I couldn't figure out how I can execute a regex that replace in a URI the "/" with "-" in an Apache rewrite rule expression. Assuming that It would be possible for as many "/" as existing in the incoming URI.

I tried ^\/?(([a-z0-9_\.-]+)\/)+$ and tested with $1-$2 for example1/example2 but i didn't work.

Can anyone help me with this ?

Thanks

Upvotes: 2

Views: 114

Answers (2)

Rounin
Rounin

Reputation: 29463

The following lines in mod_rewrite in .htaccess in the root folder, or in the vhost configuration file in your Apache :

RewriteEngine On

RewriteRule (.*)([^\/]+)\/([^\/]+)\/?$ http://%{HTTP_HOST}$1$2-$3

will rewrite

http://%{HTTP_HOST}/example1/example2

as

http://%{HTTP_HOST}/example1-example2

and

http://%{HTTP_HOST}/example1/example2/example3/example4

as

http://%{HTTP_HOST}/example1-example2-example3-example4

Upvotes: 2

Jairo
Jairo

Reputation: 426

Why not just use

\/    '-'

preferably with the 'g' flag to replace every slash in the Uri. That way (in javascript)

"example1/example2".replace(/\//, '-');

returns

"example1-example2"

Upvotes: 0

Related Questions