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.
You're telling it to replace spaces with blank, instead of a single space. Your second parameter to preg_replace is an empty string.
For this, you need:
In your version, you're eliminating all whitespace sequences with one or more elements.
...should do everything you want