php regex - can't find the error - php

Just one simple, specific question:
I've got the string {var1}12345{var2}, and I want to get the variable names used.
if (preg_match("/{([a-zA-Z0-9]*)}/g", $url, $matches)) {
print_r($matches);
}
If I remove the global flag, it works, but I only get the first variable, as expected. Why isn't it working with a global flag? It works when I'm testing it with the Regex Tester

From PHP: preg_match:
preg_match() returns the number of times pattern matches. That will be either 0 times (no match) or 1 time because preg_match() will stop searching after the first match. preg_match_all() on the contrary will continue until it reaches the end of subject. preg_match() returns FALSE if an error occurred.

Use preg_match_all to fetch several matches:
if (preg_match_all("/{([a-zA-Z0-9]*)}/", $url, $matches)) {
print_r($matches[1]);
}

This should do the trick (in case you need variables in format {name}):
$url = "{var1}12345{var2}";
if (preg_match_all("/{[a-zA-Z0-9]*}/", $url, $matches)) {
print_r($matches);
}

Related

Regex: Finding number by capturing but excluding

I'm new to regex and I am really bad at it.
I've been trying to solve this problem but still can't get the result. So, I'm hoping that someone is able to assist me. thanks!
$str = "/tqrfq_58533_13";
preg_match_all('/\d+(?>=_)*/', $str, $matches);
print_r($matches); // gets 58533, 13
but I only want '58533' and not both numbers. So I want the array of $matches to return '58533' as the only number
Use /(?<=_)(\d+)(?=_)/ as pattern in preg_match() that match digits between _
$str = "/tqrfq_58533_13";
preg_match('/(?<=_)(\d+)(?=_)/', $str, $matches);
echo $matches[0];
// 58533
Check result in demo
Also you can use preg_replace() if you don't want to get array as result
echo preg_replace('/.*?_(\d+)_.*/', "$1", $str);
// 58533
preg_match_all('/\d+(?=_)/', $str, $matches);
If you want to get only one number, remove * part since it means the result will be more than one. AFAIK, there is no such things like (?>=_). I use (?=_) to indicate that _ immediately follow the number.
You can see this link for more clarification.

preg_grep function does not find anything (php)

I hate to ask that kind of question because the answer is either 'I am stupid' or 'there is strange problem with my computer'... (and the first one is probably the right one) But I am stuck on that :
$matches = preg_grep("(.+)","ThisIsATest");
error_log(count($matches), 3, "php.log");
The log gives me 0, no matter what I give as a pattern... I can't understand why this $matches variable is always empty !
preg_grep is not for searching through a string, but an array of strings... You should probably use preg_match instead.
This is the error you should be getting:
preg_grep() expects parameter 2 to be array, string given
This is a way to return one match (and you will only have 1 in this case) with preg_match:
preg_match("(.+)","ThisIsATest", $matches);
print_r($matches);
See IDEONE demo
To access the value using $matches[0], you need to use preg_match_all:
preg_match_all("(.+)","ThisIsATest", $matches);
print_r($matches[0]);
See another demo
It seems that you are just using the wrong method:
if (preg_match('/(.+)/', "ThisIsATest")) {
# Successful match
} else {
# Match attempt failed
}

PHP preg match to store only capitalised letters, anywhere in string [duplicate]

This question already has answers here:
How to use preg_match to extract data?
(5 answers)
Closed 8 years ago.
I'm working with an API where I receive error messages such as:
{"message":"Contact is suppressed. ERROR_CONTACT_SUPPRESSED"}
I'm trying to take these error messages and just translate them into some sort of value or code so that I can provide good responses to the user rather than just a generic error.
The only thing in the error I can see that is always true is that the last portion is capitalised. Such as ERROR_CONTACT_SUPPRESED or ERROR_CONTACT_INVALID.
I know that preg_match can be used to get the uppercase characters but I believe they also have to be within a certain order/number of chars from the beginning or the end. How can I get only the capitalised section back?
I found the following but just got a result of 0 which is obviously incorrect
$result = preg_match("/^([A-Z]+)/", $result);
echo $result . '<br />';
Use this:
if(preg_match('/[A-Z_]*/', $string, $matches)) {
var_dump($matches);
}
Please read the documentation of preg_match. The function does not return the matched string as you may have expected:
preg_match() returns 1 if the pattern matches given subject, 0 if it does not, or FALSE if an error occurred.
Try this:
if(preg_match('/[A-Z_]+[^a-z]/', $string, $matches)) {
var_dump($matches);
}
It will ignore capitalised letters at the beginning of words.
Try using preg_match this way:
$str = '{"message":"Contact is suppressed. ERROR_CONTACT_SUPPRESSED"}';
preg_match("/([A-Z_]+)(?=\")/", $str, $match);
echo $result = $match[0] . '<br />';
The reason the pattern didn't match before was mainly because you indicated to match [A-Z] at the beginning of the line, which it wasn't =! (^[A-Z]). You also need to indicate the other characters present, which would include the underscore.

preg_match - get match with just one statement

I am wondering if it's possible to get a regex match in PHP by only using one statement? This question is more of a challenge to see if this is possible.
Right now you have to do something like this:
preg_match('#(\d+)$#', $subject, $match);
echo $match[1];
How do I access $match with one statement, instead of two?
I don't want to use preg_replace.
If it's possible with a closure, the better. I love fancy code.
I don't think it's possbile. the third argument $matches is always an array. From the PHP docs:
If matches is provided, then it is filled with the results of search.
$matches[0] will contain the text that matched the full pattern,
$matches[1] will have the text that matched the first captured
parenthesized subpattern, and so on.
Source: http://www.php.net/manual/en/function.preg-match.php
If you have a lot of regexes that only have one group of capturing parentheses, you could make a shortcut function for your purpose:
function preg_match_one($regex, $subject) {
if(preg_match($regex, $subject, $matches)) {
return $matches[1];
}
else {
return false;
}
}

Regex s modifier, not working?

Okay, I am a noob to regex, and I am using this site for my regex primer:
Question: using the s modifier, the code below is suppose to echo 4 as it has found 4 newline characters.
However, when I run this I get one(1), why?
link text
<?php
/*** create a string with new line characters ***/
$string = 'sex'."\n".'at'."\n".'noon'."\n".'taxes'."\n";
/*** look for a match using s modifier ***/
echo preg_match("/sex.at.noon/s", $string, $matches);
/*The above code will echo 4 as it has found 4 newline characters.*/
?>
Use preg_match_all() instead which doesn't stop after the first match.
preg_match() returns the number of times pattern matches. That will be either 0 times (no match) or 1 time because preg_match() will stop searching after the first match. preg_match_all() on the contrary will continue until it reaches the end of subject . preg_match() returns FALSE if an error occurred. —PHP.net
However, the code will output still only 1 because what you are matching is the regex "sex.at.noon" and not a line break.
preg_match() will only ever return 0 or 1 because it stops after the first time the pattern matches. If you use preg_match_all() it will still return 1 because your pattern only matches once in the string you're matching against.
If you want the number of newlines via regex:
echo preg_match_all("/\n/m", $string, $matches);
Or via string functions:
echo substr_count($string, "\n");

Categories