Question

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.

Was it helpful?

Solution 2

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

OTHER TIPS

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. 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
$to= xyz@ab.com,aaa@abc.com,bbb@abd.com,cc@abe.com;

$toArr = preg_split('[\,]', $to);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top