Jump to content


Photo

Finding Chacters in a string


  • Please log in to reply
5 replies to this topic

#1 steve m

steve m
  • Members
  • PipPipPip
  • Advanced Member
  • 50 posts

Posted 06 October 2006 - 01:13 AM

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?

#2 krausehaus2

krausehaus2
  • Members
  • PipPip
  • Member
  • 12 posts

Posted 06 October 2006 - 01:24 AM

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.

#3 printf

printf
  • Staff Alumni
  • Advanced Member
  • 889 posts

Posted 06 October 2006 - 01:26 AM

use a preg_ function and put all the character you want to accept inside [] and then test the string!

<?

$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


?>



me!

#4 steve m

steve m
  • Members
  • PipPipPip
  • Advanced Member
  • 50 posts

Posted 06 October 2006 - 01:34 AM

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.

#5 printf

printf
  • Staff Alumni
  • Advanced Member
  • 889 posts

Posted 06 October 2006 - 01:53 AM

^ = matches the beginning of a string or (line if you use the /m modifier)
$ = matches the end of a string or (line 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!

#6 steve m

steve m
  • Members
  • PipPipPip
  • Advanced Member
  • 50 posts

Posted 06 October 2006 - 02:00 AM

Thanks, I understand it now.  You have been a great help.  Thanks again.




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users