简体   繁体   中英

php regex replace slashes and spaces and hyphens

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM