preg_replace non-alpha, leave single whitespaces

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.

Answers


$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


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


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.


Need Your Help

Convert Chinese Pinyin with accents to numerical form

php nlp cjk

I'm looking to convert Pinyin where the tone marks are written with accents (e.g.: Nín hǎo) to Pinyin written in numerical/ASCII form (e.g.: Nin2 hao1).

execute query onload page

php javascript jquery html mysql

I want to execute a query during onload. How do I this?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.