loop
loop

Reputation: 229

php preg_match() code for comma separated names

I need to validate input patterns using preg_match() so that the patterns is like " anyname1,anyname2,anyname3, ".

Note that there is a comma at the end too. Any letter or number is valid between the commas, numbers do not have to appear at the end. e.g "nam1e,Na2me,NNm22," is valid.

I tried ^([A-Za-z0-9] *, *)*[A-Za-z0-9]$ but did no work. I have gone through other posts too but did not get a perfect answer.

Can someone give me an answer for this?

Upvotes: 3

Views: 6210

Answers (5)

Pheu Verg
Pheu Verg

Reputation: 230

How about something like

function implodeForRegex($itemRex, $glue) {
    return "(" . $itemRex . $glue ")*" . $itemRex;
}
...
preg_match('/' . implodeForRegex('([\d]+)', ',') . '/', $string)

Upvotes: 0

SierraOscar
SierraOscar

Reputation: 17637

If you just want the actual values without the comma, then you can simply use this:

\w+(?=[,])

http://regex101.com/r/xT6wE4/1

Upvotes: 3

vks
vks

Reputation: 67968

^([a-zA-Z0-9]+,)+$

You can simply do this.See demo.

http://regex101.com/r/yR3mM3/8

Upvotes: 0

Stephen
Stephen

Reputation: 18917

It sounds like you want to validate that the string contains a series of comma separated alpha-numeric substrings, with an optional trailing comma.

In that situation, this should achieve what you want.

$str = "anyname1,anyname2,anyname3,";

$re = '~^([a-z0-9]+,)+$~i';

if (preg_match($re, $str)) {
    // String matches the pattern!
}
else {
    // Nope!
}

If the value stored in $str contains a trailing space like in your example, and you don't want to use trim() on the value, the following regex will allow for whitespace at the end of $str:

~^([a-z0-9]+,)+\s*$~i

Upvotes: 2

KIKO Software
KIKO Software

Reputation: 16688

Why use such a complex solution for a simple problem? You can do the same in two steps:

1: trim spaces, line feeds, line returns and comma's:

$line = trim($line," \r\n,");

2: explode on comma's to see all the names:

$array = explode(',',$line);

You're not telling us what you're going to use it for, so I cannot know which format you really need. But my point is that you don't need complex string functions to do simple tasks.

Upvotes: 1

Related Questions