1

As the title reads, I'm trying to replace all non-alpha characters and replace all double (or more) white spaces to a single one. I simply can't get around the white spaces stuff.

So far my preg_replace line:

$result = trim( preg_replace( '/\s+/', '', strip_tags( $data->parent_label ) ) );

Note: The strip_tags and trim is needed.


EDIT: This is what I came up with:

/**
 * Removes all non alpha chars from a menu item label
 * Replaces double and more spaces into a single whitespace
 * 
 * @since 0.1
 * @param (string) $item
 * @return (string) $item
 */
public function cleanup_item( $item )
{
    // Regex patterns for preg_replace()
    $search = [
        '@<script[^>]*?>.*?</script>@si', // Strip out javascript 
        '@<style[^>]*?>.*?</style>@siU',  // Strip style tags properly 
        '@<[\/\!]*?[^<>]*?>@si',          // Strip out HTML tags
        '@<![\s\S]*?–[ \t\n\r]*>@',       // Strip multi-line comments including CDATA
        '/\s{2,}/',
        '/(\s){2,}/',
    ];
    $pattern = [
        '#[^a-zA-Z ]#', // Non alpha characters
        '/\s+/',        // More than one whitespace
    ];
    $replace = [
        '',
        ' ',
    ];
    $item = preg_replace( $search, '', html_entity_decode( $item ) );
    $item = trim( preg_replace( $pattern, $replace, strip_tags( $item ) ) );

    return $item;
}

Maybe the last strip_tags() isn't necessary. It's just there to be sure.

kaiser
  • 21,817
  • 17
  • 90
  • 110
  • Possible duplicate of http://stackoverflow.com/questions/2326125/remove-multiple-whitespaces-in-php – hafichuk Nov 30 '11 at 16:10
  • @hafichuk Yea, if you only consider the title. As this would have exceeded the title lenght, the `trim` and `strip_tags` were left out, as they're already present in the code line. Thanks. – kaiser Nov 30 '11 at 16:41

3 Answers3

4
$patterns = array (
  '/\W+/', // match any non-alpha-numeric character sequence, except underscores
  '/\d+/', // match any number of decimal digits
  '/_+/',  // match any number of underscores
  '/\s+/'  // match any number of white spaces
);

$replaces = array (
  '', // remove
  '', // remove
  '', // remove
  ' ' // leave only 1 space
);

$result = trim(preg_replace($patterns, $replaces, strip_tags( $data->parent_label ) ) );

...should do everything you want

DaveRandom
  • 87,921
  • 11
  • 154
  • 174
3

You're telling it to replace spaces with blank, instead of a single space. Your second parameter to preg_replace is an empty string.

Tesserex
  • 17,166
  • 5
  • 66
  • 106
3

replace all double (or more) white spaces to a single one

For this, you need:

preg_replace( '/\s+/', ' ', $subject)

In your version, you're eliminating all whitespace sequences with one or more elements.

Artefacto
  • 96,375
  • 17
  • 202
  • 225