How to know string regardless of proper format - php

I have variable like this
$string = "Hello World";
I want to compare its with properly format:
$formatstring = 'anystringornumber/anystringornumber/anystringornumber/anystringornumber/number';
This is my PHP usage:
$key = "Kode Parkir 1/01012015/Shift1/Suhendra/25000";
$regex = '^[A-Za-z]/[A-Za-z]/[A-Za-z]/[A-Za-z]/[0-9]^';
if (preg_match($regex, $key)) {
echo 'Passed';
} else {
echo 'Wrong key';
}
The result always Wrong Key.

Your regex is incorrect instead use
$regex = '~[a-z\d]+/[a-z\d]+/[a-z\d]+/[a-z\d]+/[\d]+~i';
Demo

You want to match alphanumeric character (letter and number), but didn't add the numbers in the regex. Also you missed + to match multiple characters. Secondly don't use ^ for enclosing the pattern. It is used as a special character in regex, which means start of string. You can use # instead. Like this:
$regex = '#[A-Za-z0-9]+/[A-Za-z0-9]+/[A-Za-z0-9]+/[A-Za-z0-9]+/[0-9]+#';
But if you want to use ^ and $ with their special meaning it will be like this :
$regex = '#^[A-Za-z0-9]+/[A-Za-z0-9]+/[A-Za-z0-9]+/[A-Za-z0-9]+/[0-9]+$#';

Related

Check matching values using php pregmatch

How to check matching value using preg_match in PHP. Could you please check below samples and help me write a regular expression?
Sample values are
1: sam.s_655
2: sara.t_993
3: suyathi.s_633
4: siraj.t_912
<?php
$val = 'sara.t_993';
if (preg_match('', $val)) {
print "Got match!\n";
}
?>
Try this.
$val = "sara.t_993";
if (preg_match('#^[a-z]+\.[a-z]{1}_[0-9]{3}$#', $val)) {
print "Got match!\n";
}
[a-z]+ = one or more a-z
\. = one dot, dot must be escaped, is a special char in regex
[a-z]{1} = one a-z
_ = one undercore
[0-9]{3} = three numbers
^ ... $ = for full match , so siraj.t_912abc wont match
I think this is the match you are looking for:
preg_match('/^\w*\.\w\_\d{3}$/', $look);

php regex does not contain any of the following words

Im using the following regex to check if a string contains any of the following words:
/(work|hello|yes)/
How could I reverse it, to check if the string instead does not contain any of the following words?
if (preg_match('/(work|hello|yes)/', trim(strtolower($mystring)))) {
}
Note I dont want to use !preg_match
Could use a negative looakhead to match the string, if it does not contain the words:
^(?!.*?(?:work|hello|yes)).*
Also might want to add \b word boundaries, before/after the word.
Test at regex101.com
If it's multiline input, use with s (PCRE_DOTALL) flag to make the . also match newlines.
Try this :
$match = '/work|hello|yes/';
$myString = trim(strtolower($mystring));
if (preg_match($match,$myString)) {
}
You missed ' first parameter of preg_match
$mystring='hello world';
if (preg_match('/(work|hello|yes)/', trim(strtolower($mystring)))) {
echo 'Yes'; //Result is yes
}else{
echo 'No';
}

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.

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);
?>

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