PHP preg_split remove commas and trailing white-space

家住魔仙堡 提交于 2019-12-04 18:22:39

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

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