preg_place非字母,保留单个空格 [英] preg_replace non-alpha, leave single whitespaces

查看:24
本文介绍了preg_place非字母,保留单个空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所示,我正在尝试替换所有非字母字符,并将所有双(或更多)空格替换为单个空格。我就是绕不开空格的东西。

到目前为止我的preg_replace行:

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

注意:strip_tagstrim是必需的。


编辑:这是我想出来的:

/**
 * 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
        '@<![sS]*?–[ 	

]*>@',       // 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;
}

可能最后的strip_tags()不是必需的。只是为了确保它在那里。

推荐答案

$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 ) ) );

.应该做您想做的一切

这篇关于preg_place非字母,保留单个空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆