preg_replace non-alpha, leave single whitespaces(preg_place非字母,保留单个空格)
本文介绍了preg_place非字母,保留单个空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
正如标题所示,我正在尝试替换所有非字母字符,并将所有双(或更多)空格替换为单个空格。我就是绕不开空格的东西。
到目前为止我的preg_replace行:
$result = trim( preg_replace( '/s+/', '', strip_tags( $data->parent_label ) ) );
注意:strip_tags和trim是必需的。
编辑:这是我想出来的:
/**
* 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非字母,保留单个空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
织梦狗教程
本文标题为:preg_place非字母,保留单个空格
基础教程推荐
猜你喜欢
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- 如何替换eregi() 2022-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
