PHP preg_match special characters only - php

I try to find a preg_match that filters strings that contain only special characters like -.
However, the string itself can contain special characters but it should not be special characters only.
Any ideas how to do that?
Result should return true if string only contains special characters. So something like
if(preg_match('//',$string)) echo $string; //I leave the pattern empty as this is the actual question.

You need to match the string for any alphanumeric character.
$one= "%^&";
$two = "asd%asd";
function notOnlySpecialChars($str) {
if (preg_match('/[A-Za-z0-9]/', $str)) { //Replaced _ with -
return true;
} else {
return false;
}
}
notOnlySpecialChars($one); //false
notOnlySpecialChars($two); //true

Related

Compare username to regular expression with PHP

I've never used regular expressions before and did some research on how to allow my username field only alphanumeric characters, dashes, dots, and underscores. I have the following expression but it doesn't seem to be working.
$string = "Joe_Scotto";
if (!preg_match('[a-zA-Z0-9_-.]', $string)) {
echo "Does not match Regex";
} else {
echo "Matches";
}
I want the statement to return true if it is following the "guidelines" and false if the username contains something other than what I specified it should contain. Any help would be great. Thanks!
Try this
$string = "Joe_Scotto";
if (!preg_match('/^[A-Za-z0-9_.]+$/', $string)) {
echo "Does not match Regex";
} else {
echo "Matches";
}
You match only a single character. Try this:
$string = "Joe_Scotto";
if (!preg_match('/^[a-zA-Z0-9_.-]+$/', $string)) {
echo "Does not match Regex";
} else {
echo "Matches";
}
The + sign says: match 1 or more characters defined directly before the + (* is the same but matches 0 or more characters).
Also the separators '/' (or any other separator characters) are required.
And in character classes, it is better to place the - sign to the end, else it could be misinterpreted as range from _ to .
And add ^ at the beginning (this means: match from the beginning of the input) and $ to the end (this means: match to the end of the input). Else, also a part of the string would match.
You should use something like that http://www.phpliveregex.com/p/ern
$string = 'John_Buss';
if (preg_match('/[A-z0-9_\-.]+/', $string)) {
return true;
} else {
return false;
}
Make sure to add / delimiter character at the start and the end of your regex
Make sure to use \ escape character before -
Make sure to add + character quantifier

identify a string having special charactor

I have no. of strings and i want to identify those string which have special characters.
I am trying this to do above
if (!preg_match('/[^A-Za-z0-9]/', $url)) {
echo "special character";
}
And I have also tried:
if (ctype_alnum($url)) {
echo "special character";
}
The character i want to allow are a-z, A-Z, 0-9,_,-,/
And my string containing special character is like
torbjörn-hallber etc.
how can i do that ? please help.
Your first attempt with preg_match was good, just don't negate the return value.
if (preg_match('/[^A-Za-z0-9]/', $url)) {
echo 'special character';
}
You want to allow more characters including /, so I use ~ as a delimiter.
if (preg_match('~[^a-z0-9/_-]~i', $url)) {
echo 'special character';
}

php validate string with preg_match

I am trying to verify in PHP with preg_match that an input string contains only "a-z, A-Z, -, _ ,0-9" characters. If it contains just these, then validate.
I tried to search on google but I could not find anything usefull.
Can anybody help?
Thank you !
Use the pattern '/^[A-Za-z0-9_-]*$/', if an empty string is also valid. Otherwise '/^[A-Za-z0-9_-]+$/'
So:
$yourString = "blahblah";
if (preg_match('/^[A-Za-z0-9_-]*$/', $yourString)) {
#your string is good
}
Also, note that you want to put a '-' last in the character class as part of the character class, that way it is read as a literal '-' and not the dash between two characters such as the hyphen between A-Z.
$data = 'abc123-_';
echo preg_match('/^[\w|\-]+$/', $data); //match and output 1
$data = 'abc..';
echo preg_match('/^[\w|\-]+$/', $data); //not match and output 0
You can use preg_replace($pattern, $replacement, $subject):
if (preg_replace('/[A-Za-z0-9\-\_]/', '', $string)) {
echo "Detect non valid character inside the string";
}
The idea is to remove any valid chars, if the result is NOT empty do the code.

How to validiate for a solely alphabetic string with spaces in PHP?

I know that there is the function ctype_alpha, though this one will return FALSE when the string contains spaces (white space character).
How do I allow alpha characters and spaces, but nothing else?
$is_alpha_space = ctype_alpha(str_replace(' ', '', $input)));
or
$is_alpha_space = preg_match('/^[a-z\s]*$/i', $input);
if (preg_match("^/[a-zA-Z ]+$/", $input)) {
// input matches
}
Demo: http://ideone.com/jp6Wi
Docs: http://php.net/manual/en/function.preg-match.php
ctype_alpha(preg_replace('/\s/', '', $mystring))
The inner expression returns the string without spaces, and then you use ctype_alpha`` as you wish
Removing the spaces is the way to go, but remember ctype_alpha results in a false on an empty string these days! Below the method I use...
function validateAlpha($valueToValidate, $spaceAllowed = false) {
if ($spaceAllowed) {
$valueToValidate = str_replace(' ', '', $valueToValidate);
}
if (strlen($valueToValidate) == 0) {
return true;
}
return ctype_alpha($valueToValidate);
}
I would work around with a Simple regex and with the php function preg_match() like this:
if(preg_match("/^[a-zA-Z ]+$/", $varToCheck)){
//your code here
}
The important part here is the regex that identifies the parts you want, in my case I wanted text for a name field and with spaces like the case in here.[a-z] is the range from a to z, A-Z are the range from A to Z and the " " at the end represents the spaces.
Hope this helps someone.

preg_match special characters

How can I use preg_match to see if special characters [^'£$%^&*()}{#:'#~?><>,;#|\-=-_+-¬`] exist in a string?
[\W]+ will match any non-word character.
but to match only the characters from the question, use this:
$string="sadw$"
if(preg_match("/[\[^\'£$%^&*()}{#:\'#~?><>,;#\|\\\-=\-_+\-¬\`\]]/", $string)){
//this string contain atleast one of these [^'£$%^&*()}{#:'#~?><>,;#|\-=-_+-¬`] characters
}
Use preg_match. This function takes in a regular expression (pattern) and the subject string and returns 1 if match occurred, 0 if no match, or false if an error occurred.
$input = 'foo';
$pattern = '/[\'\/~`\!##\$%\^&\*\(\)_\-\+=\{\}\[\]\|;:"\<\>,\.\?\\\]/';
if (preg_match($pattern, $input)){
// one or more matches occurred, i.e. a special character exists in $input
}
You may also specify flags and offset for the Perform a Regular Expression Match function. See the documentation link above.
My function makes life easier.
function has_specchar($x,$excludes=array()){
if (is_array($excludes)&&!empty($excludes)) {
foreach ($excludes as $exclude) {
$x=str_replace($exclude,'',$x);
}
}
if (preg_match('/[^a-z0-9 ]+/i',$x)) {
return true;
}
return false;
}
The second parameter ($excludes) may be passed with values you wish to ignore.
Usage
$string = 'testing_123';
if (has_specchar($string)) {
// special characters found
}
$string = 'testing_123';
$excludes = array('_');
if (has_specchar($string,$excludes)) { } // false
For me, this works best:
$string = 'Test String';
$blacklistChars = '"%\'*;<>?^`{|}~/\\#=&';
$pattern = preg_quote($blacklistChars, '/');
if (preg_match('/[' . $pattern . ']/', $string)) {
// string contains one or more of the characters in var $blacklistChars
}
You can use preg_quote to escape charaters to use inside a regex expression:
preg_match('/' . preg_quote("[^'£$%^&*()}{#:'#~?><>,;#|\-=-_+-¬`]", '/') . '/', $string);
http://php.net/manual/en/function.preg-quote.php
This works well for all PHP versions. The resultant is a bool and needs to be used accordingly.
To check id the string contains characters you can use this:
preg_match( '/[a-zA-Z]/', $string );
To check if a string contains numbers you can use this.
preg_match( '/\d/', $string );
Now to check if a string contains special characters, this one should be used.
preg_match('/[^a-zA-Z\d]/', $string);
In case you want to match on special characters
preg_match('/[\'\/~`\!##\$%\^&\*\(\)_\-\+=\{\}\[\]\|;:"\<\>,\.\?\\\]/', $input)

Categories