Solved

PHP regular expression

Posted on 2014-11-17
7
202 Views
Last Modified: 2014-11-17
Hi.

I'm trying to check if a string has a list of numbers separed by commas. Any element separed by comma could be also an asterisk (*) instead of a number.

Here some examples of valid expressions:
123,456,23
123,*,23
345
*
*,123,*,456

And some non-valid expressions:
*,a,*
*,123,

I'm trying this regular expression:
/[0-9|\*](,([0-9]|\*)*/

I tested it on this page: https://es.functions-online.com/preg_match.html
however it seems it always return 1. Isn't preg_match the correct function to call for this purpose? What I'm doing wrong?

Thank you.
0
Comment
Question by:gplana
7 Comments
 
LVL 82

Expert Comment

by:Dave Baldwin
ID: 40448127
REGEX always drives me nuts.  I figure it out for the thing I'm working on and then I forget most of it.  So the next time, I go back to this page http://php.net/manual/en/function.preg-match.php and figure it out again.  Check out the PCRE link at the bottom of the page also.
0
 
LVL 74

Expert Comment

by:käµfm³d 👽
ID: 40448175
Try:

([0-9]+|\*)(,([0-9]+|\*))*

Open in new window


It appears that only the first part of your pattern is broken. You're trying to put the alternation inside of the character class (i.e. the square brackets).
0
 
LVL 15

Author Comment

by:gplana
ID: 40448279
Thanks kaufmed, but I tryied your expression (just surrounding it by / as delimiter character) on the link https://es.functions-online.com/preg_match.html and trying with this text "*,121,a" return a result of 1. It seems like it returns a result of 1 always.
0
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 15

Author Comment

by:gplana
ID: 40448281
I'm leaving third and fourth parameters empty. Is that ok?
0
 
LVL 74

Accepted Solution

by:
käµfm³d   👽 earned 500 total points
ID: 40448385
You'll need to include start of string ( ^ ) and end of string ( $ ) anchors, then:

/^([0-9]+|\*)(,([0-9]+|\*))*$/

Open in new window

0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 40448388
Sometimes it's easier to get it all right if you break it down into components and not try to do it all with a single regular expression.  Here's my take on the problem.
http://iconoun.com/demo/temp_gplana.php

<?php // demo/temp_glpana.php
error_reporting(E_ALL);
echo '<pre>';

// SEE http://www.experts-exchange.com/Programming/Languages/Scripting/PHP/Q_28564006.html

// TEST CASES
$tests = array
( '123,456,23'
, '123,*,23'
. '345'
, '*'
, '*,123,*,456'

, '*,a,*'
, '*,123,'
)
;

// RUN THE TEST CASES
foreach ($tests as $test)
{
    echo PHP_EOL . htmlentities($test);
    if (valid_substrings($test)) echo ' VALID';
        else echo ' INVALID';
}


// A FUNCTION TO TEST THE SUBSTRINGS
function valid_substrings($str)
{
    // A REGULAR EXPRESSION TO DISALLOW ANYTHING BUT NUMBERS OR THE ASTERISK
    $rgx
    = '#'       // REGEX DELIMITER
    . '^'       // AT START OF STRING
    . '['       // START CHARACTER CLASS
    . '^'       // NEGATION - MATCH ANYTHING NOT THESE CHARACTERS
    . '0-9'     // NUMBERS
    . '\*'      // ESCAPED ASTERISK
    . ']'       // ENDOF CHARACTER CLASS
    . '$'       // AT ENDOF STRING
    . '#'       // REGEX DELIMITER
    ;

    // BREAK ON COMMAS AND TEST EACH SUBSTRING
    $subs = explode(',', $str);
    foreach ($subs as $sub)
    {
        if (empty($sub))            return FALSE;
        if (preg_match($rgx, $sub)) return FALSE;
    }
    return TRUE;
}

Open in new window

0
 
LVL 15

Author Closing Comment

by:gplana
ID: 40448429
Excellent. This was my problem: I needed an start of string and an end of string. Thank you for teaching me in that.

Regards.
0

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Introduction HTML checkboxes provide the perfect way for a web developer to receive client input when the client's options might be none, one or many.  But the PHP code for processing the checkboxes can be confusing at first.  What if a checkbox is…
This article will explain how to display the first page of your Microsoft Word documents (e.g. .doc, .docx, etc...) as images in a web page programatically. I have scoured the web on a way to do this unsuccessfully. The goal is to produce something …
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to count occurrences of each item in an array.

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now