Check if string contains the same pattern - php

How can I check if a string has a specific pattern like this?
XXXX-XXXX-XXXX-XXXX
4 alphanumeric characters then a minus sign, 4 times like the structure above.
What I would like to do is that I would like to check if a string contains this structure including "-".
I'm lost, can anyone point me in the correct direction?
Example code:
$string = "5E34-4512-ABAX-1E3D";
if ($pattern contains this structure XXXX-XXXX-XXXX-XXXX) {
echo 'The pattern is correct.';
}
else {
echo 'The pattern is invalid.';
}

Use regular expressions
<?php
$subject = "XXXX-XXXX-XXXX-XXXX";
$pattern = '/^[a-zA-Z0-9]{4}\-[a-zA-Z0-9]{4}\-[a-zA-Z0-9]{4}\-[a-zA-Z0-9]{4}$/';
if(preg_match($pattern, $subject) == 1);
echo 'The pattern is correct.';
} else {
echo 'The pattern is invalid.';
}
?>
[a-zA-Z0-9] match a single character
{4} matches the character Exactly 4 times
\- matches a escaped hyphen

With a perl regexp :
$string = "5E34-4512-ABAX-1E3D";
if (preg_match('/\w{4}-\w{4}-\w{4}-\w{4}/',$string)) {
echo 'The pattern is correct.';
}

use preg_match :
$ok = preg_match('/^([0-9A-Z]{4}-){3}[0-9A-Z]{4}$/', $string)
And if you want to consider lowercase characters, use :
$ok = preg_match('/^([0-9A-Z]{4}-){3}[0-9A-Z]{4}$/i', $string)

Related

Space in # mention username and lowercase in link

I am trying to create a mention system and so far I've converted the #username in a link. But I wanted to see if it is possible for it to recognise whitespace for the names. For example: #Marie Lee instead of #MarieLee.
Also, I'm trying to convert the name in the link into lowercase letters (like: profile?id=marielee while leaving the mentioned showed with the uppercased, but haven't been able to.
This is my code so far:
<?php
function convertHashtags($str) {
$regex = '/#+([a-zA-Z0-9_0]+)/';
$str = preg_replace($regex, strtolower('$0'), $str);
return($str);
}
$string = 'I am #Marie Lee, nice to meet you!';
$string = convertHashtags($string);
echo $string;
?>
You may use this code with preg_replace_callback and an enhanced regex that will match all space separated words:
define("REGEX", '/#\w+(?:\h+\w+)*/');
function convertHashtags($str) {
return preg_replace_callback(REGEX, function ($m) {
return '$0';
}, $str);
}
If you want to allow only 2 words then you may use:
define("REGEX", '/#\w+(?:\h+\w+)?/');
You can filter out usernames based on alphanumeric characters, digits or spaces, nothing else to extract for it. Make sure that at least one character is matched before going for spaces to avoid empty space match with a single #. Works for maximum of 2 space separated words correctly for a username followed by a non-word character(except space).
<?php
function convertHashtags($str) {
$regex = '/#([a-zA-Z0-9_]+[\sa-zA-Z0-9_]*)/';
if(preg_match($regex,$str,$matches) === 1){
list($username,$name) = [$matches[0] , strtolower(str_replace(' ','',$matches[1]))];
return "<a href='profile?id=$name'>$username</a>";
}
throw new Exception('Unable to find username in the given string');
}
$string = 'I am #Marie Lee, nice to meet you!';
$string = convertHashtags($string);
echo $string;
Demo: https://3v4l.org/e2S8C
If you want the text to appear as is in the innerHTML of the anchor tag, you need to change
list($username,$name) = [$matches[0] , strtolower(str_replace(' ','',$matches[1]))];
to
list($username,$name) = [$str , strtolower(str_replace(' ','',$matches[1]))];
Demo: https://3v4l.org/dCQ4S

Regular Expression not working in PHP

How to check below line in regular expression?
[albums album_id='41']
All are static except my album_id. This may be 41 or else.
Below my code I have tried but that one not working:
$str = "[albums album_id='41']";
$regex = '/^[albums album_id=\'[0-9]\']$/';
if (preg_match($regex, $str)) {
echo $str . " is a valid album ID.";
} else {
echo $str . " is an invalid ablum ID. Please try again.";
}
Thank you
You need to escape the first [ and add + quantifier to [0-9]. The first [ being unescaped created a character class - [albums album_id=\'[0-9] and that is something you did not expect.
Use
$regex = '/^\[albums album_id=\'[0-9]+\']$/';
Pattern details:
^ - start of string
\[ - a literal [
albums album_id=\'- a literal string albums album_id='
[0-9]+ - one or more digits (thanks to the + quantifier, if there can be no digits here, use * quantifier)
\'] - a literal string ']
$ - end of string.
See PHP demo:
$str = "[albums album_id='41']";
$regex = '/^\[albums album_id=\'[0-9]+\']$/';
if (preg_match($regex, $str)) {
echo $str . " is a valid album ID.";
} else {
echo $str . " is an invalid ablum ID. Please try again.";
}
// => [albums album_id='41'] is a valid album ID.
You have an error in your regex code, use this :
$regex = '/^[albums album_id=\'[0-9]+\']$/'
The + after [0-9] is to tell that you need to have one or more number between 0 and 9 (you can put * instead if you want zero or more)
To test your regex before using it in your code you can work with this website regex101

How to know string regardless of proper format

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]+$#';

preg_match issues using php variable

I have a variable I want to use in a preg_match combined with some regex:
$string = "cheese-123-asdf";
$find = "cheese";
if(preg_match("/$find-/d.*/", $string)) {
echo "matched";
}
In my pattern I am trying to match using cheese, followed by a - and 1 digit, followed by anything else.
change /d to \d
there is no need to use .*
if your string is defined by user (or may contains some characters (e.g: / or * or ...)) this may cause problem on your match.
Code:
<?php
$string = "cheese-123-asdf";
$find = "cheese";
if(preg_match("/$find-\d/", $string))
{
echo "matched";
}
?>
You mistyped / for \:
if(preg_match("/$find-\d.*/", $string)) {
The .* is also not really necessary since the pattern will match either way.
for digit, it's \d
if(preg_match("/$find-\d.*/", $string)) {

Allow only [a-z][A-Z][0-9] in string using PHP

How can I get a string that only contains a to z, A to Z, 0 to 9 and some symbols?
You can filter it like:
$text = preg_replace("/[^a-zA-Z0-9]+/", "", $text);
As for some symbols, you should be more specific
You can test your string (let $str) using preg_match:
if(preg_match("/^[a-zA-Z0-9]+$/", $str) == 1) {
// string only contain the a to z , A to Z, 0 to 9
}
If you need more symbols you can add them before ]
Don't need regex, you can use the Ctype functions:
ctype_alnum: Check for alphanumeric character(s)
ctype_alpha: Check for alphabetic character(s)
ctype_cntrl: Check for control character(s)
ctype_digit: Check for numeric character(s)
ctype_graph: Check for any printable character(s) except space
ctype_lower: Check for lowercase character(s)
ctype_print: Check for printable character(s)
ctype_punct: Check for any printable character which is not whitespace or an alphanumeric character
ctype_space: Check for whitespace character(s)
ctype_upper: Check for uppercase character(s)
ctype_xdigit: Check for character(s) representing a hexadecimal digit
In your case use ctype_alnum, example:
if (ctype_alnum($str)) {
//...
}
Example:
<?php
$strings = array('AbCd1zyZ9', 'foo!#$bar');
foreach ($strings as $testcase) {
if (ctype_alnum($testcase)) {
echo 'The string ', $testcase, ' consists of all letters or digits.';
} else {
echo 'The string ', $testcase, ' don\'t consists of all letters or digits.';
}
}
Online example: https://ideone.com/BYN2Gn
Both these regexes should do it:
$str = preg_replace('~[^a-z0-9]+~i', '', $str);
Or:
$str = preg_replace('~[^a-zA-Z0-9]+~', '', $str);
A shortcut will be as below also:
if (preg_match('/^[\w\.]+$/', $str)) {
echo 'Str is valid and allowed';
} else
echo 'Str is invalid';
Here:
// string only contain the a to z , A to Z, 0 to 9 and _ (underscore)
\w - matches [a-zA-Z0-9_]+
Hope it helps!
If you need to preserve spaces in your string do this
$text = preg_replace("/[^a-zA-Z0-9 ]+/", "", $text);
Please note the way I have added space between 9 and the closing bracket. For example
$name = "!#$John Doe";
echo preg_replace("/[^a-zA-Z0-9 ]+/", "", $name);
the output will be:
John Doe
Spaces in the string will be preserved.
If you fail to include the space between 9 and the closing bracket the output will be:
JohnDoe
Hope it helps someone.
The best and most flexible way to accomplish that is using regular expressions.
But I`m not sure how to do that in PHP but this article can help. link

Categories