Regular Expression not working in PHP - 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

Related

PHP regular expression to match multiple email ID formats

I am trying to obtain the local part of an email ID using regex.
The challenge here is that the local part comes in two different formats and I need to figure out which format I'm reading and prepare the alternate form of that email ID. As always the snippet of my code that does this is pasted below.
$testarray = array("user1#gmail.com", "user2.tp#gmail.com", "user3#gmail.com", "user4.tp#gmail.com", "user5.tp#gmail.com");
foreach($testarray as $emailID) {
preg_match("/([\w\d]*)\.([\w\d]*)#gmail.com/", $emailID, $match);
if ($match[2] == "tp") {
$altform = $match[1] . "#gmail.com";
} else {
$altform = $match[1] . ".tp#gmail.com";
}
error_log("ALTERNATE FORM OF $emailID IS $altform");
}
The problem I'm facing here is I'm not getting the desired result as neither $match[1] and $match[2] match anything for "user1#gmail.com".
You need to use an optional group around the dot + word chars subpattern, and then check if the group matched after executing the search:
foreach($testarray as $emailID) {
$altform = "";
if (preg_match("/(\w+)(?:\.(\w+))?#gmail\.com/", $emailID, $match))
{
if (!empty($match[2]) && $match[2] == "tp") {
$altform = $match[1] . "#gmail.com";
} else {
$altform = $match[1] . ".tp#gmail.com";
}
}
print_r("ALTERNATE FORM OF $emailID IS $altform\n");
}
See the online PHP demo.
Notes on the pattern:
(\w+) - Capturing group 1: one or more word chars
(?:\.(\w+))? - 1 or 0 occurrences (due to ? quantifier) of:
\. - a dot
(\w+) - Capturing group 2: one or more word chars
#gmail\.com - a literal string #gmail.com (note the . is escaped to match a literal dot).

Check if string contains the same pattern

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)

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)) {

regex how would i search for asterisk-space-equals sign?

what regex would be used to search for an asterisk followed by a space followed by an equlas sign?
that is '* =' ?
Using preg_match in php would find a match in these strings:
'yet again * = it happens'
'again* =it happens'
and what is simplest way to search for an exact word for word, number for number, puncuation sign for puncuation sign string in regex?
You don't need a regular expression here. Consider using strpos
$pos = strpos('yet again * = it happens', '* =');
if(pos === false){
// not there
}
else {
// found
}
If you must use preg_match, remember the delimiters:
preg_match('/\* =/', $str, $matches);
In this case you have to escape the asterisk. You may want to allow more spaces, for example with the pattern \*\h+=. \h stands for horizontal whitespace characters.
Try this regex pattern
\*(?=\s=)
<?php
function runme($txt) {
return preg_match("/^\*\ \=$/", $txt);
}
echo runme($argv[1])? "$argv[1] matches!\n" : "$argv[1] is not asterisk space equals-sign\n";
?>
$ php asterisk_space_equals.php 'yet again * = it happens'
yet again * = it happens is not asterisk space equals-sign
$ php asterisk_space_equals.php 'again* =it happens'
again* =it happens is not asterisk space equals-sign
$ php asterisk_space_equals.php '* ='
* = matches!

Attempting to understand handling regular expressions with php

I am trying to make sense of handling regular expression with php. So far my code is:
PHP code:
$string = "This is a 1 2 3 test.";
$pattern = '/^[a-zA-Z0-9\. ]$/';
$match = preg_match($pattern, $string);
echo "string: " . $string . " regex response: " , $match;
Why is $match always returning 0 when I think it should be returning a 1?
[a-zA-Z0-9\. ] means one character which is alphanumeric or "." or " ". You will want to repeat this pattern:
$pattern = '/^[a-zA-Z0-9. ]+$/';
^
"one or more"
Note: you don't need to escape . inside a character group.
Here's what you're pattern is saying:
'/: Start the expressions
^: Beginning of the string
[a-zA-Z0-9\. ]: Any one alphanumeric character, period or space (you should actually be using \s for spaces if your intention is to match any whitespace character).
$: End of the string
/': End the expression
So, an example of a string that would yield a match result is:
$string = 'a'
Of other note, if you're actually trying to get the matches from the result, you'll want to use the third parameter of preg_match:
$numResults = preg_match($pattern, $string, $matches);
You need a quantifier on the end of your character class, such as +, which means match 1 or more times.
Ideone.

Categories