How to parse a string of function parameters with REGEX in PHP - php

I am trying to handle parameters like Java or PHP natively handle them, using Regex to parse variable numbers (and types) of arguments. For example, a function might be:
util.echo(5, "Hello, world!");
In this instance, I would want to separate 5 as the first argument and "Hello, world!" as the second (without quotes). What I currently do is explode by commas, but that runs into issues if the string parameters include a comma. I don't have much experience with Regex, but I think it has some way of ignoring commas that are within quotes.
The Regex from this question (",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)") seems like it could work, but I'm confused on how to implement it with PHP.

To test a regular expression onto a string, you can use the preg_match() function in PHP.
See the manual
// $matches is going to output the matches
preg_match("/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/", $to_be_checked, $matches);
if($matches){
var_dump($matches);
// there was a match!
} else {
// the regular expression did not find any pattern matches
}
if you don't need to access the exact matches, just if there was at least one pattern match, you can simply do this:
if(preg_match("/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/", $to_be_checked)){
// there was a match!
} else {
// the regular expression did not find any pattern matches
}

Thank you to Zac and The fourth bird! Example solution that works, for future reference:
$parameters = 'util.echo(5, "Hello, world!");';
preg_match_all('/(?:[^\s(]+\(|\G(?!^),\s*)\K(?:"[^"]*"|[^,()]+)(?=[^()]*\);)/', $parameters, $matches);
if($matches){
var_dump($matches[0]);
} else {
echo('No matches.');
}

Related

PHP preg_match regular expression for find date in string

I try to make system that can detect date in some string, here is the code :
$string = "02/04/16 10:08:42";
$pattern = "/\<(0?[1-9]|[12][0-9]|3[01])\/\.- \/\.- \d{2}\>/";
$found = preg_match($pattern, $string);
if ($found) {
echo ('The pattern matches the string');
} else {
echo ('No match');
}
The result i found is "No Match", i don't think that i used correct regex for the pattern. Can somebody tell me what i must to do to fix this code
First of all, remove all gibberish from the pattern. This is the part you'll need to work on:
(/0?[1-9]|[12][0-9]|3[01]/)
(As you said, you need the date only, not the datetime).
The main problem with the pattern, that you are using the logical OR operators (|) at the delimiters. If the delimiters are slashes, then you need to replace the tube characters with escaped slashes (/). Note that you need to escape them, because the parser will not take them as control characters. Like this: \/.
Now, you need to solve some logical tasks here, to match the numbers correctly and you're good to go.
(I'm not gonna solve the homework for you :) )
These articles will help you to solve the problem tough:
Character classes
Repetition opetors
Special characters
Pipe character (alternation operator)
Good luck!
In your comment you say you are looking for yyyy, but the example says yy.
I made a code for yy because that is what you gave us, you can easily change the 2 to a 4 and it's for yyyy.
preg_match("/((0|1|2|3)[0-9])\/\d{2}\/\d{2}/", $string, $output_array);
Echo $output_array[1]; // date
Edit:
If you use this pattern it will match the time too, thus make it harder to match wrong.
((0|1|2|3)[0-9])/\d{2}/\d{2}\s+\d{2}:\d{2}:\d{2}
http://www.phpliveregex.com/p/fjP
Edit2:
Also, you can skip one line of code.
You first preg_match to $found and then do an if $found.
This works too:
If(preg_match($pattern, $string, $found))}{
Echo $found[1];
}Else{
Echo "nothing found";
}
With pattern and string as refered to above.
As you can see the found variable is in the preg_match as the output, thus if there is a match the if will be true.

Regex fomatting and design for a query

I'm having a some trouble formatting my regular expression for my PHP code using preg_match().
I have a simple string usually looking like this:
"q?=%23asdf".
I want my regular expression to only pass true if the string begins with "q?=%23" and there is a character at the end of the 3. So far one of the problems I have had is that the ? is being pulled up by the regex so doing something like
^q?=23 doesn't work. I am also having problems with contiguous searching in Regex expressions (because I can't figure out how to search after the 3).
So for clarification: "q?=%23asd" should PASS and "q?=%23" should FAIL
I'm no good with Regex so sorry if this seems like a beginner question and thanks in advance.
Just use a lookahead to check whether the character following 3 is an alphabet or not,
^q\?=%23(?=[a-zA-Z])
Add . instead of [A-Za-z] only if you want to check for any character following 3,
^q\?=%23(?=.)
Code would be,
$theregex = '~^q\?=%23(?=[a-z])~i';
if (preg_match($theregex, $yourstring)) {
// Yes! It matches!
}
else { // nah, no luck...
}
So the requirement is: Start with q?=%23, followed by at least one [a-z], the pattern could look like:
$pattern = '/^q\?=%23[a-z]+/i';
Used i (PCRE_CASELESS) modifier. Also see example at regex101.
$string = "q?=%23asdf";
var_dump(figureOut($string));
function figureOut($string){
if(strpos($string, 'q?=%23') == 0){
if(strlen($string) > 6){
return true;
}else{ return false;}
}
}

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;
}
}

Matching multiple variables using regex (PHP/JS)

I understand how to use PHP's preg_match() to extract a variable sequence from a string. However, i'm not sure what to do if there are 2 variables that I need to match.
Here's the code i'm interested in:
$string1 = "help-xyz123#mysite.com";
$pattern1 = '/help-(.*)#mysite.com/';
preg_match($pattern1, $string1, $matches);
print_r($matches[1]); // prints "xyz123"
$string2 = "business-321zyx#mysite.com";
So basically I'm wondering how to extract two patterns: 1) Whether the string's first part is "help" or "business" and 2) whether the second part is "xyz123" vs. "zyx321".
The optional bonus question is what would the answer look like written in JS? I've never really figured out if regex (i.e., the code including the slashes, /..../) are always the same or not in PHP vs. JS (or any language for that matter).
The solution is pretty simple actually. For each pattern you want to match, place that pattern between parentheses (...). So to extract any pattern use what've you already used (.*). To simply distinguish "help" vs. "business", you can use | in your regex pattern:
/(help|business)-(.*)#mysite.com/
The above regex should match both formats. (help|business) basically says, either match help or business.
So the final answer is this:
$string1 = "help-xyz123#mysite.com";
$pattern1 = '/(help|business)-(.*)#mysite.com/';
preg_match($pattern1, $string1, $matches);
print_r($matches[1]); // prints "help"
echo '<br>';
print_r($matches[2]); // prints "xyz123"
The same regex pattern should be usable in Javascript. You don't need to tweak it.
Yes, Kemal is right. You can use the same pattern in javascript.
var str="business-321zyx#mysite.com";
var patt1=/(help|business)-(.*)#mysite.com/;
document.write(str.match(patt1));
Just pay attention at the return value from the functions that are different.
PHP return an array with more information than this code in Javascript.

Find if a String is Contained in Delimiters in PHP

I have a string like this:
$string = '[Canada] [United States]';
I need to detect something like this
if($string contains Canada) {
// Do stuff for Canada
}
You could pull out all text between [ and ] and then see if it is found in the resulting array.
preg_match_all('/\[(.*?)\]/', $string, $matches);
if (in_array('Canada', $matches[1])) {
echo 'Hello, Canada!';
}
CodePad.
If you just used substring searching functions, you'd run the risk that the string you searched for was the substring of a larger block between brackets.
If you are doing simple text matching, and don't want the overhead of using the regular expressions engines, the strpos function may be what you are looking for.
See the PHP Manual page for strpos for more details.
if(strpos($string,"Canada")!==FALSE){
// Do stuff for Canada
}
The use of the strpos() function is preferred over strstr() due to the manual stating that for instances that the programmer only cares about finding a match, not where the match is located, strpos() is faster and less memory intensive.
Use strstr().

Categories