• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 529
  • Last Modified:

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

0
hankknight
Asked:
hankknight
  • 2
2 Solutions
 
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
 
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now