Solved

PHP regular expression

Posted on 2014-11-17
7
206 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 83

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 75

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
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
LVL 15

Author Comment

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

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 109

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

Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Why is my wamp get_include_path() wrong? 2 21
What is wrong with this PDO Delete Query? 2 18
selector:validator cookies 4 30
Php logic to add to date card 9 24
Whatever be the reason, if you are working on web development side,  you will need day-today validation codes like email validation, date validation , IP address validation, phone validation on any of the edit page or say at the time of registration…
I imagine that there are some, like me, who require a way of getting currency exchange rates for implementation in web project from time to time, so I thought I would share a solution that I have developed for this purpose. It turns out that Yaho…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
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…

821 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