Re: simple regex query

From: Date: Fri, 07 Apr 2006 00:06:17 +0000
Subject: Re: simple regex query
References: 1 2  Groups: php.general 
Request: Send a blank email to php-general+get-233358@lists.php.net to get a copy of this message
Jochem Maas wrote:
Angelo Zanetti wrote:
Hi guys Been tryin to figure out regex and have found some tutorials but some have made things clear and others have confused me. Anyway for a simple query, if I just wanted to check that a variable has only text and numeric characters would I do something like this (i want it to fail if it finds a symbol eg: + - { " etc...): echo "REG result: " . preg_match('/[a-zA-Z0-9]*/', '{d-fg');
you're on the right path, whats needed is start and end [string] delimiters in the regexp (note I used a different regexp delimiter, '#', which is irrelevant): echo "REG 1 result: ", preg_match("#[a-zA-Z0-9]*#", "{d-fg"), "\n",
     "REG 2 result: ", preg_match("#^[a-zA-Z0-9]*$#", "{d-fg"), "\n";
the magic characters are '^' andf '$' as explained in more detail here: http://php.net/manual/en/reference.pcre.pattern.syntax.php <quote> ^
    assert start of subject (or line, in multiline mode)
$
    assert end of subject (or line, in multiline mode)
</quote>
thanks but I think I kinda got working the other way around: if (!preg_match('/[^a-zA-Z0-9]/', 'gf-5'))
     echo "valid";
else
     echo "invalid";
then if I wanted to list any symbols I could just change it to: preg_match('/[^a-zA-Z0-9\,\.]/', 'gf-5')) if I wanted . and , to be accepted. tx

« previous php.general (#233358) next »