Regex PHP preg_match priority - php

I have this code
if (preg_match('/J[a-zA-Z0-9]+S/', $id)) {
echo "1";
}
else if (preg_match('/BUT[a-zA-Z0-9]+TN/', $id)) {
echo "2";
}
I have the id as BUTEqHLHxJSRr9DJZSMTN, Instead of getting 2 as output, I am getting 1.
This is has BUTEqHLHxJSRr9DJZSMTN which is making it match with the first expression. But this exp also has BUT/TN and it should also match with that regex also right?
Is there any way I can make the regex pattern in such a way that it do not check for matches from the middle of an expression, but rather it should match the beginning and end.
I don't know whether this is a stupid question to ask,but is there anyway its possible to prevent pregmatch to match from the begining?

You can use the ^ (beginning of string), $ (end of string) anchors to match an entire string.
For example, this will give you the result of 2 seeing how it matches the entire string from start to end.
$id = 'BUTEqHLHxJSRr9DJZSMTN';
if (preg_match('/^J[a-zA-Z0-9]+S$/', $id)) { echo "1"; }
else if(preg_match('/^BUT[a-zA-Z0-9]+TN$/', $id)) { echo "2"; }

Use word boundaries to avoid matching unwanted text:
if(preg_match('/\bJ[a-zA-Z0-9]+S\b/', $id)) {
echo "1";
}
else if(preg_match('/\bBUT[a-zA-Z0-9]+TN\b/', $id)) {
echo "2";
}

try ^ then it will check must be start from given string
if(preg_match('/^J[a-zA-Z0-9]+S/', $id)) {
echo "1";
}
else if(preg_match('/^BUT[a-zA-Z0-9]+TN/', $id)) {
echo "2";
}

Related

PHP verify url ends in two parts of path, one fixed and one variable

I have urls on my site like:
http://example.com/item/one/
http://example.com/item/two/
http://example.com/item/one/something
http://example.com/item/two/someotherthing
http://example.com/other/one/
http://example.com/other/two/
And I want to check the url and redirect if it matches /item/one/ or /item/two/ but NOT if it matches just /one/ or /two/, and NOT matching any string that goes deeper like something.
Ideally, I would want to match anything that contains both /item/ and one final path after that (ie /item/three/,/item/four/ as well).
What would be the best way to accomplish the match? preg_match (not sure how to write it for this)? explode?
UPDATE
Tried the following:
$thisurl = $_SERVER['REQUEST_URI'];
if (preg_match("/^\/item\/(.*)\/$/", $thisurl)) {
echo "it matches";
} else {
echo "nope nope nope";
}
Which works in this tester, but fails in my code (because it also matches true for things like:
http://example.com/item/one/something
http://example.com/item/two/someotherthing
which it should not.
This regex does the job:
~/item/[^/]+/$~i
Explanation:
~ : regex delimiter
/item/ : literally
[^/]+ : 1 or more character that is NOT a slash
/ : a slash
$ : end of string
~i : regex delimiter + case insensitive
In use:
$tests = array(
'http://example.com/item/one/',
'http://example.com/item/two/',
'http://example.com/item/one/something',
'http://example.com/item/two/someotherthing',
'http://example.com/other/one/',
'http://example.com/other/two/'
);
foreach($tests as $test) {
echo "$test --> ";
if (preg_match('~/item/[^/]+/$~i', $test)) {
echo "valid\n";
} else {
echo "invalid\n";
}
}
Output:
http://example.com/item/one/ --> valid
http://example.com/item/two/ --> valid
http://example.com/item/one/something --> invalid
http://example.com/item/two/someotherthing --> invalid
http://example.com/other/one/ --> invalid
http://example.com/other/two/ --> invalid
This is how you could do it using the explode function.
$url = [
'http://example.com/item/one/',
'http://example.com/item/two/',
'http://example.com/item/one/something',
'http://example.com/item/two/someotherthing',
'http://example.com/other/one/',
'http://example.com/other/two/'
];
foreach($url as $row){
$path = explode('/',str_replace('http://example.com/','',rtrim($row,'/')));
if(count($path) != 2){
continue;
}
if($path[0] != "item"){
continue;
}
if(in_array($path[1],[
'one',
'two'
])){
echo 'redirect...';
}
}
However a better answer would probably involve using some form of regex.
Finally got it working with this:
if (preg_match("/^\/item\/[-a-z]+\/$/", $thisurl)) { //matches any lowercase word that may or may not contain a dash
echo "it matches";
} else {
echo "nope nope nope";
}
DESPITE this page telling me that preg_match("/^\/item\/(.*)\/$/", $thisurl) would work, it did not.

user of preg_match and preg_replace

<?php
$flag=true;
if(isset($_POST['sub'])){
if(isset($_POST['text'])){
$a=$_POST["text"];
} else {
$a='';
}
if(!empty($_POST['msg'])){
$b=$_POST['msg'];
$c=strlen($b);}
if(isset($_POST['wrd'])){
$d=($_POST["wrd"]);
} else {
$d='';
}
if(preg_match("[\w\s.,a-zA-Z$a,\.]",$b)){
$flag=false;
}
if($flag){
$i;
for($i=0;$i<=$c;$i++)
{
$newtext = str_replace($a,$d,$b);
echo $newtext;
echo "</br>";
break;
}
} else {
echo"not found ";}
}
?>
This is my code I want to match word(paragraph) from a original paragraph but the problem is this.
In one line the word (paragraph) is written like this (paragraph,) and (paragraph.)
That's why preg_match is not able to find the these two word and same goes to preg_replace also.
This is incorrect:
if(preg_match("[\w\s.,a-zA-Z$a,\.]",$b))
Regex needs start and end delimiters. It should be:
if(preg_match("/[\w\s.,a-zA-Z$a,\.]/", $b))
Also note that your regex is also incorrect. I can see few mistakes (there myay be more):
inside square brackets you don't need to escape dot
you seem to have another dot that will match ANY character
You have \w that means word character hence you don't need separate a-zA-Z
You have a misplaced a after $ sign

Check some words with preg_match

I need to check some words with preg_match. If the words contain numbers and ., I want to echo "ok".
Lets say i want to ckeck this :
4814.84dszs //ok
412.84.61.412 //ok
hello.4you //ok
welcome.user //not ok
481221222 // not ok
I have used this:
if (preg_match('/^[0-9][.]+$/', 'MY_WORD_HERE'))
{
echo 'ok';
}
But it doesn't give me the exactly result which I looking for.
Try this :
if (preg_match('/(\d+\.)|(\.\d+)/', '4814.84dszs'))
{
echo 'ok';
}
^ -> indicates at the begining of the string
$ -> End of the string.
So your pattern says from start to end(Matching for whole string)
If you remove this it will match anywhere in the string not whole string.
$pattern = '#^([\d]{1,3})([.][\d]{1,3})([.][\d]{1,3})([.][\d]{1,3})$#';
Use this:
if (preg_match('/([0-9]+[\.]+|[\.]+[0-9]+)$/', 'MY_WORD_HERE'))
{
echo 'ok';
}
"+" (plus sign) means 1 or more occurrences of the matched expression
You can also use this if the . and the numbers are not following each other and there are other chars in the middle:
if (preg_match('/([0-9]+[^0-9\.]*[\.]+|[\.]+[^0-9\.]*[0-9]+)$/', 'MY_WORD_HERE'))
{
echo 'ok';
}
Explanation: it checks if there is a digit followed by dot or if there's a dot followed by a digit or even if there's a digit followed by other chars then a dot or vice versa.
try using this
$pattern = '%(?=.*[0-9])(?=.*\.)%';
if (preg_match($pattern, 'MY_WORD_HERE'))
{
echo 'ok';
}
?>

PHP - preg_match - How to match a string upper/lower case with anything before or after it?

I have a part of a function that goes like this:
if (preg_match("#\bscript\b#",$userInput))
{
$bannedWord = 'script';
logHax();
return TRUE;
}
This is causing a problem for what I am trying to accomplish because it will only match the exact word "script" and not variations of it, like "ScriPt" or "<script>".
What I would like to have is the examples of the not matched strings along with the original string return true.
How's this:
if (preg_match("/<script\b[^>]*>/i",$userInput))
{
$bannedWord = 'script';
logHax();
return TRUE;
}
Case-insensitive matching:
preg_match("#\bscript\b#i",$userInput)
Note the i. Also note that this the first example in the docs:
<?php
// The "i" after the pattern delimiter indicates a case-insensitive search
if (preg_match("/php/i", "PHP is the web scripting language of choice.")) {
echo "A match was found.";
} else {
echo "A match was not found.";
}
?>
Cheers
If you really want to match "anything" before or after the string (not just a word), then you do not even need preg_match here, bacuse you could do something like this:
$userInputLower = strtolower($userInput);
if (strpos($userInputLower, 'script') !== false)
{
$bannedWord = 'script';
logHax();
return TRUE;
}

customizing preg_match

How do i preg_match an string to match the following format in php:
$m="123/456789/01";
if(pregmatch(????, $m){
// match
}else{
// doesn't match
}
i.e. 3 digits + "/" + 6 digits + "/" + 2 digits.
This is my try :)
if(preg_match('/[0-9]{3}\/[0-9]{6}\/[0-9]{2}/', $m)
{
// match
}
else
{
// Doesn't match
}
if (preg_match("#\d{3}/\d{6}/\d{2}#", $string)) {
// yeah
} else {
// nope
}
have a look at Pattern Syntax specifically Escape sequences.
Depending on what you would like to parse, regular expressions are not always needed:
$m="123/456789/01";
if(3 == count(sscanf($m, '%d/%d/%d'))) {
// match
}else{
// doesn't match
}

Categories