简体   繁体   English

PHP preg_split 删除逗号和尾随空格

[英]PHP preg_split remove commas and trailing white-space

The code below has been taken directly from PHP: preg_split - Manual下面的代码直接取自PHP:preg_split - 手册

Example #1 preg_split() example : Get the parts of a search string Example #1 preg_split() 示例:获取搜索字符串的部分

<?php
// split the phrase by any number of commas or space characters,
// which include " ", \r, \t, \n and \f
$keywords = preg_split("/[\s,]+/", "hypertext language, programming");
print_r($keywords);
?>

The above example will output:上面的例子将输出:

Array
(
    [0] => hypertext
    [1] => language
    [2] => programming
)

I am creating a tagging system which will allow people to type anything into a text box and upon return the text will be processed and inserted into the database.我正在创建一个标记系统,它允许人们在文本框中输入任何内容,返回时文本将被处理并插入到数据库中。 The data could be one word or a phrase, if more than one tag is typed, it will be split using a comma.数据可以是一个词或一个短语,如果输入了多个标签,它将使用逗号分隔。

Therefore I would like to be able to keep "hypertext language" as is, so only strip the white-space at the beginning and end of the string and also any white-space after a comma, but not between words which may be phrases.因此,我希望能够按原样保留“超文本语言”,因此仅去除字符串开头和结尾的空格以及逗号后的任何空格,但不能去除可能是短语的单词之间的空格。

I think it'is the best choice.我认为这是最好的选择。

$keywords = preg_split('/\s*,\s*/', "hypertext language, programming", -1, PREG_SPLIT_NO_EMPTY);

First of all "Regex is much slower" is wrong, because it's always depends on the pattern.首先, “Regex 慢得多”是错误的,因为它总是取决于模式。 In this case preg_split() is faster.在这种情况下 preg_split() 更快。

Second preg_split is more readable and as practice shows more profitable option.第二个preg_split 更具可读性,实践表明更有利可图的选择。 Keep it simple.把事情简单化。

$b = "hypertext language, programming";

$time = microtime(1);
for ($i=1; $i<100000; $i++)
    $a = array_map('trim', explode(',', $b)); // Split by comma
printf("array_map(trim), explode  = %.2f\n", microtime(1)-$time);

$time = microtime(1);
for ($i=1; $i<100000; $i++)
    $a = preg_split('/\s*,\s*/', $b);     // Split by comma
printf("Preg split = %.2f\n", microtime(1)-$time);

array_map(trim), explode  = 0.32
Preg split = 0.22

You can use array_map() , explode() and trim() :您可以使用array_map()explode()trim()

<?php
    $keywords = array_map('trim', explode(',', 'hypertext language, programming'));
    print_r($keywords);
?>

Which will output:这将输出:

Array
(
    [0] => hypertext language
    [1] => programming
)

DEMO演示

$to= xyz@ab.com,aaa@abc.com,bbb@abd.com,cc@abe.com;

$toArr = preg_split('[\,]', $to);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM