preg_replace non-alpha, leave single whitespaces

2019-05-29 13:06发布

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.

3条回答
手持菜刀,她持情操
2楼-- · 2019-05-29 13:27

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

查看更多
做个烂人
3楼-- · 2019-05-29 13:35

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.

查看更多
做个烂人
4楼-- · 2019-05-29 13:46
$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

查看更多
登录 后发表回答