1

I have fews combinations of strings that I need to bring in to one pattern, that is multiple spaces should be removed, double hyphens should be replaced with single hypen, and single space should be replaced with single hyphen.

I have already tried this expression.

$output = preg_replace( "/[^[:space:]a-z0-9]/e", "", $output );
$output = trim( $output );
$output = preg_replace( '/\s+/', '-', $output );

But this fails in few combinations.

I need help in making all of these combinations to work perfectly:

1. steel-black
2. steel- black
3. steel    black

I should also remove any of these as well \r\n\t.

1
  • 1
    can you post sample data a your desired output? Commented Aug 24, 2014 at 16:13

1 Answer 1

6

You could use something like this (thanks for the better suggestion @Robin) :

$s = 'here is  a test-- with -- spaces-and hyphens';
$s = preg_replace('/[\s-]+/', '-', $s);
echo $s;

Replace any number of whitespace characters or hyphens with a single hyphen. You may also want to use trim($s, '-') to remove any leading or trailing hyphens. It would also be possible to do this directly in the regex but I think it's clearer not to.

Output:

here-is-a-test-with-spaces-and-hyphens

If there are additional characters that you would like to remove, you can simply add them into the bracket expression, for example /[()\s-]+/ would also remove parentheses. However, you might prefer to just replace all non-word characters:

$s = 'here is  a test- with -- spaces ( ), hyphens (-), newlines
    and tabs (  )';
$s = trim(preg_replace('/[\W]+/', '-', $s), '-');
echo $s;

This replaces any number of characters other than [a-zA-Z0-9_] with a hyphen and removes any leading and trailing hyphens.

Output:

here-is-a-test-with-spaces-hyphens-newlines-and-tabs
Sign up to request clarification or add additional context in comments.

9 Comments

Is there a reason why you're not directly using preg_replace('/[\s-]+/', '-', $output) ?
@Robin for some reason that didn't occur to me...I've edited my answer to use your suggestion, thanks.
what about \r\n\t ? i think in my regex [:space:] was removing these?
also i need to remove parenthesis from the string as well
@Muhammad \s works for those characters as well. I have added to my answer to explain about removing additional characters.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.