Jump to content

Finding Chacters in a string


steve m

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?
Link to comment
https://forums.phpfreaks.com/topic/23136-finding-chacters-in-a-string/
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!
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.
^ = 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!

Archived

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

×
×
  • Create New...

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.