PHP preg_split remove commas and trailing white-space

不羁岁月 提交于 2019-12-06 14:18:16

问题


The code below has been taken directly from PHP: preg_split - Manual

Example #1 preg_split() example : Get the parts of a search string

<?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.


回答1:


You can use array_map(), explode() and trim():

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

Which will output:

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

DEMO




回答2:


I think it'is the best choice.

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

First of all "Regex is much slower" is wrong, because it's always depends on the pattern. In this case preg_split() is faster.

Second preg_split is more readable and as practice shows more profitable option. 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


来源:https://stackoverflow.com/questions/19572738/php-preg-split-remove-commas-and-trailing-white-space

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!