E4bd1595f34e7e03765eda6ed65bf6bb

I'm trying to get an input string to get rid of all characters except alpha-numerics, hyphen and a space, then the result i would like any hyphens at the start and at the end removed, also, if there are more than one hyphen in a row, to just replace it with one, and change the whole thing to lower case e.g :

-!! This is a "**Test- -string**" !!!!-

results to :

this-is-a-test-string

The code works fine, but it seems a bit long-winded the way i've done it, can this code be refactored at all?

1
$outputstr =  preg_replace('/[-]{2,}/','-',trim(strtolower(str_replace(' ','-',preg_replace('/[^A-Z0-9- ]+/i','',$inputstr))),'-'));

Refactorings

No refactoring yet !

73415a883aec7c0a7aada9c4cdb208b5

Christoffer

February 9, 2010, February 09, 2010 08:13, permalink

No rating. Login to rate!

A little longer but easier on the eyes :)

1
2
3
4
5
6
7
8
9
<?php
function clean_string($str)
{
  $str = trim(strtolower($str));
  $str = preg_replace('/\s+/i', '-', $str);
  $str = preg_replace('/[^a-z0-9\-\._]/i', '', $str);
  return $str;
}
?>
E83321ad57faa07a9d664597bacfbb6c

Max

March 4, 2010, March 04, 2010 16:04, permalink

No rating. Login to rate!

A compromise of readability and conciseness

1
2
3
4
5
6
<?php
function clean_string($str) {
  $str = trim(strtolower($str));
  return preg_replace(array('/[^\w]+/', '/(^-+|-+$|[-]{2,})/'), array('-', ''), $str);
}
?>
C7402070919f7a3c76fec48132ec8bd2

Alix Axel

May 3, 2010, May 03, 2010 00:41, permalink

No rating. Login to rate!

This does everything you asked and is the most effective function so far.

1
2
3
4
5
6
7
8
<?php

function clean_string($str)
{
    return strtolower(trim(preg_replace('~[^0-9a-z]+~i', '-', $str), '-'));
}

?>
C7402070919f7a3c76fec48132ec8bd2

Alix Axel

May 3, 2010, May 03, 2010 00:44, permalink

No rating. Login to rate!

Forgot to allow spaces in my previous solution, it's fixed now.

1
2
3
4
5
6
7
8
<?php

function clean_string($str)
{
    return strtolower(trim(preg_replace('~[^0-9a-z ]+~i', '-', $str), '-'));
}

?>

Your refactoring





Format Copy from initial code

or Cancel