PHP/REGEX: all non alphanumeric characters to a single dash

I want to replace all non alphanumeric characters with a single dash.

There should never be more than one dash in a row.

Also, the result should never end with a dash.

I want this,
This-is-a-test-and-only-a-test

Not this:
This-is-a-test--------and-only-a-test---
$string = "This is a test!!!  (((and only a test)))";
echo preg_replace("/[^a-zA-Z0-9]/", "-", $string);

Open in new window

LVL 16
hankknightAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

ikrommCommented:
jsut add a "+" sign in the regular expression.

echo preg_replace("/[^a-zA-Z0-9]+/", "-", $string);

Open in new window


This will tell the program to search for any number (more than one) of non alphanumeric strings
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Ray PaseurCommented:
use another REXEG (see example 5 on preg_replace where they eliminate excess whitespace.  You can do the same with dashes.

Then trim($str, '-') and you have the string you want.
0
Ray PaseurCommented:
See: http://www.laprbass.com/RAY_temp_hankknight.php
<?php // RAY_temp_hankknight.php
error_reporting(E_ALL);

// EXAMPLE THAT DOES NOT QUITE WORK
$string = "This is a test!!!  (((and only a test)))";
echo preg_replace("/[^a-zA-Z0-9]+/", "-", $string);

echo "<br/>";

// EXAMPLE THAT WORKS
$string = "This is a test!!!  (((and only a test)))";
echo trim(preg_replace("/[^a-zA-Z0-9]+/", "-", $string), '-');

Open in new window

0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.