php validate string with preg_match - php

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.

Related

PHP preg_replace help trim special characters

I tried to search around but couldn't find anything useful. I need to trim special characters from beginning and end of a string and identify if the remaining portion is a number.
For example
(5)
[[12]]
{3}
#!8(#
!255=
/879/
I need a preg_match expression for it. The regular expression should ignore the string if any alphabets come in between.
$string="yourstring";
$new_string=preg_replace('/[^A-Za-z0-9]/', '', $string);
if(is_numeric($new_string){
echo "number";
} else {
echo "string";
}
^(?!.*[a-zA-Z])\W*(\d+)\W*$
You can use this.Lookahead will validate if only numbers are there.Replace by $1.See demo.
https://regex101.com/r/cT0hV4/2

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.

Identifying a random repeating pattern in a structured text string

I have a string that has the following structure:
ABC_ABC_PQR_XYZ
Where PQR has the structure:
ABC+JKL
and
ABC itself is a string that can contain alphanumeric characters and a few other characters like "_", "-", "+", "." and follows no set structure:
eg.qWe_rtY-asdf or pkl123
so, in effect, the string can look like this:
qWe_rtY-asdf_qWe_rtY-asdf_qWe_rtY-asdf+JKL_XYZ
My goal is to find out what string constitutes ABC.
I was initially just using
$arrString = explode("_",$string);
to return $arrString[0] before I was made aware that ABC ($arrString[0]) itself can contain underscores, thus rendering it incorrect.
My next attempt was exlpoding it on "_" anyway and then comparing each of the exploded string parts with the first string part until I get a semblance of a pattern:
function getPatternABC($string)
{
$count = 0;
$pattern ="";
$arrString = explode("_", $string);
foreach($arrString as $expString)
{
if(strcmp($expString,$arrString[0])!==0 || $count==0)
{
$pattern = $pattern ."_". $arrString[$count];
$count++;
}
else break;
}
return substr($pattern,1);
}
This works great - but I wanted to know if there was a more elegant way of doing this using regular expressions?
Here is the regex solution:
'^([a-zA-Z0-9_+-]+)_\1_\1\+'
What this does is match (starting from the beginning of the string) the longest possible sequence consisting of the characters inside the square brackets (edit that per your spec). The sequence must appear exactly twice, each time followed by an underscore, and then must appear once more followed by a plus sign (this is actually the first half of PQR with the delimiter before JKL). The rest of the input is ignored.
You will find ABC captured as capture group 1.
So:
$input = 'qWe_rtY-asdf_qWe_rtY-asdf_qWe_rtY-asdf+JKL_XYZ';
$result = preg_match('/^([a-zA-Z0-9_+-]+)_\1_\1\+/', $input, $matches);
if ($result) {
echo $matches[2];
}
See it in action.
Sure, just make a regular expression that matches your pattern. In this case, something like this:
preg_match('/^([a-zA-Z0-9_+.-]+)_\1_\1\+JKL_XYZ$/', $string, $match);
Your ABC is in $match[1].
If the presence of underscores in these strings has a low frequency, it may be worth checking to see if a simple explode() will do it before bothering with regex.
<?php
$str = 'ABC_ABC_PQR_XYZ';
if(substr_count($str, '_') == 3)
$abc = reset(explode('_', $str));
else
$abc = regexy_function($str);
?>

Extract a special hash from a string

I'm trying to extract the following pattern {#56DS1e5R9w7v} which is :
{
Hash
a-z, A-Z, 0-9 ( not necessarily an alphanumeric string )
}
Any ideas please?
Thank you
Try this pattern:
\{#([^}]*)\}
It should match all characters that are not }, and place the result in a captured group. You may want to change [^}]* to \w* or [A-Za-z0-9]* if that's problematic.
Example (also on ideone.com):
$str = "hello {#56DS1e5R9w7v} good people";
preg_match_all("/\{#([^}]*)\}/", $str, $matches);
Something like ({#[a-z0-9]+?}) ?
preg_match('/(\{#[a-z0-9]+?\})/i', $sString)
What about:
<?php
$code = '{#56DS1e5R9w7v}';
$matches = preg_match('/^\{#[a-zA-Z0-9]+\}$/', $code);
?>
This makes sure the string begins with a { the second char must be a #, the 3th char until } must be alpha numeric and it must end with a }.
Hope this helped!

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