Using regex to match a specific pattern - php

I'm trying to match any strings that doesn't start with "false1" or "false2", and ends with true, but the regex isn't matching for some reason. What am I doing wrong?
$text = "start true";
$regex = "~(?:(^false1|false2).+?) true~";
if (preg_match($regex, $text, $match)) {
echo "true";
}
Expected Result:
true
Actual Result:
null

You may use negative lookahead.
^(?!false[12]).*true$
If you really want to use boundaries then try this,
^(?!false[12]\b).*\btrue$
DEMO
Update:
^(?!.*false[12]\b).*\btrue$
(?!.*false[12]\b) negative lookahead which asserts that the string would contain any char but not the sub-string false1 or false2 and it must ends with the string true, that's why we added true$ at the last.

Related

Find a pattern in a string

I am trying to detect a string inside the following pattern: [url('example')] in order to replace the value.
I thought of using a regex to get the strings inside the squared brackets and then another to get the text inside the parenthesis but I am not sure if that's the best way to do it.
//detect all strings inside brackets
preg_match_all("/\[([^\]]*)\]/", $text, $matches);
//loop though results to get the string inside the parenthesis
preg_match('#\((.*?)\)#', $match, $matches);
To match the string between the parenthesis, you might use a single pattern to get a match only:
\[url\(\K[^()]+(?=\)])
The pattern matches:
\[url\( Match [url(
\K Clear the current match buffer
[^()]+ Match 1+ chars other than ( and )
(?=\)]) Positive lookahead, assert )] to the right
See a regex demo.
For example
$re = "/\[url\(\K[^()]+(?=\)])/";
$text = "[url('example')]";
if (preg_match($re, $text, $match)) {
var_dump($match[0]);;
}
Output
string(9) "'example'"
Another option could be using a capture group. You can place the ' inside or outside the group to capture the value:
\[url\(([^()]+)\)]
See another regex demo.
For example
$re = "/\[url\(([^()]+)\)]/";
$text = "[url('example')]";
if (preg_match($re, $text, $match)) {
var_dump($match[1]);;
}
Output
string(9) "'example'"

Target message to match with regex

I have to check csv files live and match some expression to get data.
These files can have different type of message so different matching expression.
The message can be something like that
GuiPrinter.ProcessPrint of 116806 25374 K356 S Black Face.png 229 at 1
table
And I want to get 116806 25374 K356 S Black Face.png
. So the regex associate to this kind of file would be something like (GuiPrinter.ProcessPrint of )(.*)([.][png|jpg|jpeg|PNG|JPG|JPEG]*) and I can return $result[2]
But the message and the regex can change, so I need a common function that can return the string that I want based on the regex, the function would have message and regex parameters. Maybe for another file the string that I want would be on first position so my $result[2] won't work.
How can I ensure to always return the string that I want to match ?
Use
\preg_match('/GuiPrinter.ProcessPrint of(.*?)\.(gif|png|bmp|jpe?g)/', $str, $match);
print_r($match[1]);
You could match the text GuiPrinter.ProcessPrint and then use \K to reset the starting point of the reported match.
Match any character zero or more times non greedy .*?, then match a dot \. and any of the image extensions in a non capturing group (?:gif|png|bmp|jpe?g) followed by a word boundary \b
GuiPrinter\.ProcessPrint of \K.*?\.(?:gif|png|bmp|jpe?g)\b
Note that to match the dot literally you have to escape it \.
For example to return 1 match using preg_match:
$str = 'GuiPrinter.ProcessPrint of 116806 25374 K356 S Black Face.png 229 at 1 table';
$re = '/GuiPrinter\.ProcessPrint of \K.*?\.(?:gif|png|bmp|jpe?g)\b/';
function findMatch($message, $regex) {
preg_match($regex, $message, $matches);
return array_shift($matches);
}
$result = findMatch($str, $re);
if ($result) {
echo "Found: $result";
} else {
echo "No match.";
}
Demo

Find next word after colon in regex

I am getting a result as a return of a laravel console command like
Some text as: 'Nerad'
Now i tried
$regex = '/(?<=\bSome text as:\s)(?:[\w-]+)/is';
preg_match_all( $regex, $d, $matches );
but its returning empty.
my guess is something is wrong with single quotes, for this i need to change the regex..
Any guess?
Note that you get no match because the ' before Nerad is not matched, nor checked with the lookbehind.
If you need to check the context, but avoid including it into the match, in PHP regex, it can be done with a \K match reset operator:
$regex = '/\bSome text as:\s*'\K[\w-]+/i';
See the regex demo
The output array structure will be cleaner than when using a capturing group and you may check for unknown width context (lookbehind patterns are fixed width in PHP PCRE regex):
$re = '/\bSome text as:\s*\'\K[\w-]+/i';
$str = "Some text as: 'Nerad'";
if (preg_match($re, $str, $match)) {
echo $match[0];
} // => Nerad
See the PHP demo
Just come from the back and capture the word in a group. The Group 1, will have the required string.
/:\s*'(\w+)'$/

extracting data between [ ] with preg_match php

i try to extract only the number beetween the [] from my response textfile:
$res1 = "MESSAGE_RESOURCE_CREATED Resource [realestate] with id [75739528] has been created.";
i use this code
$regex = '/\[(.*)\]/s';
preg_match($regex, $res1, $matches_arr);
echo $matches_arr[1];
my result is:
realestate] with id [75742084
Can someone help me ?
Use this:
$regex = '~\[\K\d+~';
if (preg_match($regex, $res1 , $m)) {
$thematch = $m[0];
// matches 75739528
}
See the match in the Regex Demo.
Explanation
\[ matches the opening bracket
The \K tells the engine to drop what was matched so far from the final match it returns
\d+ matches one or more digits
I assume you want to match what's inside the brackets, which means that you must match everything but a closing bracket:
/\[([^]]+)\]/g
DEMO HERE
Omit the g-flag in preg_match():
$regex = '/\[([^]]+)\]/';
preg_match($regex, $res1, $matches_arr);
echo $matches_arr[1]; //will output realestate
echo $matches_arr[2]; //will output 75739528
Your regex would be,
(?<=\[)\d+(?=\])
DEMO
PHP code would be,
$regex = '~(?<=\[)\d+(?=\])~';
preg_match($regex, $res1, $matches_arr);
echo $matches_arr[0];
Output:
75739528

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