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);
}
?>

Your refactoring





Format Copy from initial code

or Cancel