Jump to content

Archived

This topic is now archived and is closed to further replies.

steve m

Finding Chacters in a string

Recommended Posts

Hi all,  I've been trying to find a PHP function where It will look at a string to look for special chacters in a string.  For example: ., /, &. etc...  What I want to do is if it finds those characters that it comes back with an error saying "invalid Characters"  or something.  I'm not sure if I could use str_replace(), is there a PHP function were it can just find the characters that I have set in an array?

Share this post


Link to post
Share on other sites
You can try ereg().  it will look for a pattern of characters.  Like:

if (ereg("cat", "raining cats and dogs"))
{
  echo "Found 'cat' ";

it will print "found a cat"

You probably could use that in a for loop looking through your array.

Share this post


Link to post
Share on other sites
use a preg_ function and put all the character you want to accept inside [] and then test the string!

[code]<?

$string = 'abvpmt675637f7760';

// this example only allows a-zA-Z0-9

if ( ! preg_match ( "/^[a-z0-9]+$/i", $string ) )
{
echo 'bad string';
exit ();
}

// continue, good string


?>[/code]



me!

Share this post


Link to post
Share on other sites
Thanks Printf,  I've tried looking at those preg_ functions, but I don't understand some of the things in inbetween the [].  Like the example you gave, what is the ^ before [ and +$/i after the ].  That's what is confusing me.  Sorry, but I am very new to preg_ functions.

Share this post


Link to post
Share on other sites
^ = matches the beginning of a string or ([b]line[/b] if you use the /m modifier)
$ = matches the end of a string or ([b]line[/b] if you use the /m modifier)
* = match anything 0 or more times
? = match what comes before it 0 or 1 time ( example: https?:// => matches http:// or https://)
+ = match was comes before it 1 or more times
[characters or range of characters] = meta character class ( matches any class of characters contained within it's brackets!

So my example, is looking for a single line string, that allows ([a-z0-9]+) which means any character in the range of a to z or any number 0 to 9, followed by +, which means match as many as there are until ($) the end of the string, but also use (/i), case insensitive matching, which allows A to Z too!

Simple Stuff

me!

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.