473,396 Members | 1,879 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

how to test string whether it contains special characters

exoskeleton
104 100+
please help dear experts on how to test string especially in username for example wheter it contains special charater and will return invalid!

please help...TIA
Apr 18 '07 #1
21 21828
devsusen
136 100+
I prefer preg_match() in such cases. Can u tell us what sort of special chars u like to search within names?

susen
Apr 18 '07 #2
tolkienarda
316 100+
please help dear experts on how to test string especially in username for example wheter it contains special charater and will return invalid!

please help...TIA
one simple way to do that is with the strpos() function. here is a short tutorial of how it works
Expand|Select|Wrap|Line Numbers
  1. $username = 'frank!anderson';
  2. $pos = strpos($username, "!");
  3. if ($pos == -1)
  4. {
  5.    print 'dont put ! in your usernames you silly person';
  6. }
  7. else
  8. {
  9.    print 'everything is super cool and what not';
  10. }
i hope that helps other functions to look at include
strcmp()
strstr()
documentation can be found at php.net/function name
ex
http://www.php.net/strcmp

eric

oh and devsusen is right pregmatch is probably the most standard way to this. but is far to complicated for a simple mind such as myself so i always use these dumbed down versions.
Apr 18 '07 #3
exoskeleton
104 100+
I prefer preg_match() in such cases. Can u tell us what sort of special chars u like to search within names?

susen
thank you sir devsusen.. :) but how can i add characters to preg_match() in order to find not just 1 special characters like the split function that only enclosed by "[ ]" like

Expand|Select|Wrap|Line Numbers
  1. split('[/.-]', $date);
in order to find not just 1 character in an expression or given string?

i tried like for example:

Expand|Select|Wrap|Line Numbers
  1. $string = '#richa@rd';
  2. preg_match('/!@#$%^&*()/','$string');
but cant able to find anything....and he can find something if like this:

Expand|Select|Wrap|Line Numbers
  1. $string = 'richard';
  2. preg_match('/chard/','$string');
Apr 19 '07 #4
exoskeleton
104 100+
one simple way to do that is with the strpos() function. here is a short tutorial of how it works
Expand|Select|Wrap|Line Numbers
  1. $username = 'frank!anderson';
  2. $pos = strpos($username, "!");
  3. if ($pos == -1)
  4. {
  5.    print 'dont put ! in your usernames you silly person';
  6. }
  7. else
  8. {
  9.    print 'everything is super cool and what not';
  10. }
i hope that helps other functions to look at include
strcmp()
strstr()
documentation can be found at php.net/function name
ex
http://www.php.net/strcmp

eric

oh and devsusen is right pregmatch is probably the most standard way to this. but is far to complicated for a simple mind such as myself so i always use these dumbed down versions.
same with this sir... how can i add special characters to find not just 1.. yes this is possible if only 1 special character to find...

thank you sir
Apr 19 '07 #5
tolkienarda
316 100+
well my advice would be to go back to devsusen's idea. and what preg_match as i am sure you know uses regular expressions and a good tutorial on the complex world of regex is
http://weblogtoolscollection.com/regex/regex.php
and there are many more but this is php based and a good starting place
unfortunatly the functions i listed earlier can only look for one expression at a time. if you had an array of strings you were looking for say

you can use a loop
Expand|Select|Wrap|Line Numbers
  1. $string = 'adsf@ASDF!fdsa#FDSA%';
  2. $lookfor[0] = '!'
  3. $lookfor[1] = '@'
  4. $lookfor[2] = '#'
  5. $lookfor[3] = '%'
  6. $i = 0;
  7. while ($i < 4)
  8. {
  9.    $var = strpos($string, $lookfor[$i]);
  10.    if ($var != -1)
  11.    {
  12.       echo 'passed test for $lookfor[$i]';
  13.    }else
  14.    {
  15.        echo 'silly person none of those silly charcters';
  16.    }
  17.  
  18. }
now i typed this code into this forum directly so there might be a missing semi colon or paren but the basic logic will work.
(preg_match and regular expressions i have avoided for my entire programing carear because the confuse me to no end but if you can figure them out i urge you to go in that direction because they are extreamley powerful and i always feel stupid when i have a problem that could be easily solved with regex but i cannot do it without loops and if statements)

eric
Apr 19 '07 #6
exoskeleton
104 100+
thank you sir... :)
Apr 20 '07 #7
devsusen
136 100+
hi,

how can i add characters to preg_match() in order to find not just 1 special characters
To check multiple special characters u can use preg_match too. There u need to specify the characters u like to check using separator. I'm giving u an example.

Expand|Select|Wrap|Line Numbers
  1. preg_match('/[\s|\n|\t|*|@|&]/', $anyVariable); 
susen
Apr 20 '07 #8
tolkienarda
316 100+
hmm i realy need to learn that preg_match stuff it is way simpler than my loops and such.

eric
Apr 20 '07 #9
exoskeleton
104 100+
thank you sir susen and sir eric...it really helps.....more power guys
Apr 21 '07 #10
I Didnt Get It Done Using "strpos". In Which Namespace Is That Function Defined ?
Jun 26 '08 #11
Can I Have Any Alternate Methods For The Same ?
Jun 26 '08 #12
This was valuable to me, as we're designing a new social network site. But here's my modification of that script, checking for a specified set of values in an array, then checking for an empty position.

This is the code exactly as it is in action. To see it working, go to <link removed>. I dare you to get by it.

Expand|Select|Wrap|Line Numbers
  1. $forbid = array(' ','--', '-', '&quot;','!','@','#','$','%','^','&','*','(',')','_','+','{','}','|',':','"','<','>','?','[',']','\\',';',"'",',','.','/','*','+','~','`','=');
  2.     $i = 0;
  3.     while ($i < 37) {
  4.         $var = strpos($userID, $forbid[$i]);
  5.         if (!empty($var)) {
  6.             $var++;
  7.             echo "Position " . $var . " forbidden character.<br><font color='#FF0000'>Character detected is <strong>'" . $forbid[$i] . "'</strong></font><br>";
  8.             echo "<p align='left'><h2><font color='red'>Oops! Only Letters and Numbers are allowed on the User ID portion.</font></h2><br><br>Please <a href='javascript:onClick=history.go(-1)' class='divProfile'>&raquo; GO BACK &laquo;</a> and remove any spaces and special characters.</p>";
  9.             exit();
  10.         }
  11.  
  12.         $i++;
  13. }
Sep 17 '09 #13
TheServant
1,168 Expert 1GB
Thanks for your input, and welcome to Bytes. I think that rather than forbidding every character possible (black-list) it would be better to have a white-list of allowed characters. Also, what about people with hyphenated names?
Sep 17 '09 #14
hsriat
1,654 Expert 1GB
@exoskeleton
If you are talking about HTML special characters, then just do...
Expand|Select|Wrap|Line Numbers
  1. if (htmlspecialchars($string) != $string) {
  2. //it contains special chars.
  3. }
Sep 17 '09 #15
Markus
6,050 Expert 4TB
@TheServant
Furthermore, that loop is completely unnecessary. Using preg_match() you can do that in 1 line of code.
Sep 17 '09 #16
TheServant
1,168 Expert 1GB
@hsriat
hsriat, I think the OP is long gone, this is a very old post that has been dug up and put at the top of the list :(

Furthermore, that loop is completely unnecessary. Using preg_match() you can do that in 1 line of code.
Amen.
Sep 17 '09 #17
@hsriat
I'll have to give this a shot, but I'm facing a deadline here. So this will be an improvement over our beta version - but later. In the meantime, for all of you, I appreciate your input. Unfortunately, I tried a preg_match() and couldn't make it work, and there's no time to piddle with it. What the code does is verifies a userID, then if there are no special characters, and all other fields are inserted properly, establishes a series of database tables, named after the userID, in SQL. This may be a regurgitated thread, but it came in handy when I needed it. We launch our social network site October 12. There's just no time to become a PHP expert in that time frame.

Now, if I could still program that old Sperry in COBOL ... oh, well.
Sep 18 '09 #18
I should add, the user setting up their account determines their userID ... and we're not converting anything in the userID field, it simply becomes the name of several new database tables. Hence, we must forbid certain characters that can't be included in a data-table name.
Sep 18 '09 #19
TheServant
1,168 Expert 1GB
You don't have to be an expert to use preg_match. Try this:
Expand|Select|Wrap|Line Numbers
  1. if ( ! preg_match(/^[a-zA-Z0-9]+$/", $userID) ) {
  2. // Display error
  3. }
I think that will do all your code does, plus cover EVERY character other than letters and numbers.
Sep 18 '09 #20
Thank you! I'll plug this in and run a test. The other code is already live, but this can quickly take its place. I sure picked the wrong week to start learning PHP - LOL!
Sep 18 '09 #21
TheServant
1,168 Expert 1GB
No worries, let us know if you have any problems.
Sep 18 '09 #22

Sign in to post your reply or Sign up for a free account.

Similar topics

9
by: lawrence | last post by:
Someone on www.php.net suggested using a seems_utf8() method to test text for UTF-8 character encoding but didn't specify how to write such a method. Can anyone suggest a test that might work?...
13
by: usgog | last post by:
I need to implement a function to return True/false whether String A contains String B. For example, String A = "This is a test"; String B = "is is". So it will return TRUE if String A includes two...
12
by: Kamilche | last post by:
I was looking for a way to speed up detecting invalid characters in my TCP string, and thought of yet another use for the translate function! If you were to 'translate out' the bad characters, and...
6
by: Mark | last post by:
Hi, My page has a table with many columns such that the right-side of the table gets chopped off when printed. I specify a table width of 100%, but otherwise no cell dimensions are specified. ...
17
by: Tom | last post by:
Is there such a thing as a CONTAINS for a string variable in VB.NET? For instance, I want to do something like the following: If strTest Contains ("A","B", "C") Then Debug.WriteLine("Found...
26
by: alberto | last post by:
Hi. Im newbie in C language. I have a binary file with many character arrays of 50 character defined as char array But in some cases, many of these 50 characters are not being used. I would...
14
by: Shhnwz.a | last post by:
Hi, I am in confusion regarding jargons. When it is technically correct to say.. String or Character Array.in c. just give me your perspectives in this issue. Thanx in Advance.
13
by: titan nyquist | last post by:
How do you test a string to see if it contains special characters? I want to ensure that any names typed into my form has only letters (and maybe allow a dash and an apostrophe). I can loop...
4
by: smartic | last post by:
how to test string whether it contains special characters -------------------------------------------------------------------------------- please help dear experts on how to test string...
5
by: Sobin Thomas | last post by:
Hi All, I want to pass a string that contains many special characters (: \ . _ etc) to another page in my website through query string. In my project I have a Gridview control ,in which there...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.