Olaf Erlandsen
Olaf Erlandsen

Reputation: 6036

How to extract string separated by comma with PHP?

I need extract a string separated by comma or comma and space. Example:

<?php
    //regexp
    $regexp = "/(select\s+(?<name>[a-z0-9]+)\s+(?<values>[^\d]+[a-z0-9]+\s*(\s*,|\s*$)))/";
    //text
    $text = "select this string1,string_2,string_3 ,string_4, string5,string_6";
    //prepare
    $match = array();
    preg_match( $regexp , $text , $match );
    //print
    var_dump( $match);
?>

I created this regexp:

(?<values>[^\d]+[a-z0-9]+\s*(\s*,|\s*$))

But this does not work perfectly.

Thanks!

Upvotes: 0

Views: 1942

Answers (2)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89557

I suggest you to use something like ~(?|select ([^\W_]+) | *([^\W,]+) *,?), if you want to check that you obtain only alphanumeric characters. Example:

$subject = 'select this string1,string_2,string_3 ,string_4, string5,string_6';
$pattern = '~(?|select ([a-z][^\W_]*+) | *+([a-z][^\W,_]*+) *+,?)~i';

preg_match_all($pattern, $subject, $matches);

if (isset($matches[1])) {
    $name = array_shift($matches[1]);
    $strings = $matches[1];
}

Or another way:

$pattern = '~select \K[a-z][^\W_]*+| *+\K[a-z][^\W,]*+(?= *,?)~';
preg_match_all($pattern, $subject, $matches);

if (isset($matches[0])) {
    $name = array_shift($matches[0]);
    $strings = $matches[0];
}

Upvotes: 1

Ibu
Ibu

Reputation: 43810

I would use preg_split for this:

$text = "select this string1,string_2,string_3 ,string_4, string5,string_6";
$stringArray = preg_split("/,\s*/",$text);

But it would be much easier to just split after each comma and then trim the result:

$stringArray = explode(",",$text);

Upvotes: 5

Related Questions