PHP regex numbers in url - php

I've got a blog, I want to display ADS or special text on the MAIN page but not on any other page with the URI /?paged=[number]. I've tried the standard regex /^[0-9].$/ but it fails to match.
I'm not sure what I've done wrong or how to go about doing this
if (substr_count($_SERVER[REQUEST_URI], "/") > 0 AND
substr_count($_SERVER[REQUEST_URI], "/?paged=1") == 0 AND
substr_count($_SERVER[REQUEST_URI], "/?paged=2") == 0 AND
substr_count($_SERVER[REQUEST_URI], "/?paged=3") == 0 AND
substr_count($_SERVER[REQUEST_URI], "/?paged=4") == 0 AND
substr_count($_SERVER[REQUEST_URI], "/?paged=5") == 0) {
echo "display special text, banners, and other stuff";
}
This is how I'm doing it currently, but I don't want to do thousands of these...

Can you not just check for the presence of paged in the GET array?
if(!isset($_GET['paged'])) {
// You know this is the main page.
}

Try this:
if (preg_match('#paged=\d+#', $_SERVER[REQUEST_URI]) {
echo "display special text, banners, and other stuff";
}

Regex: /^[0-9].$/ would be correct for "3k" string. Analize this patterns
/page=(\d+)/
/page=([1-5])/
/^\/\?page=([1-5])$/
/page=(?<page>[1-5])/

Why not using the regexp in the GET parameter ?
<?php
$regexp = "/^(\d+)+$";
if (preg_match($regexp, $_GET['paged'])) {
#...your code
} else {
#...your code
}
Or (if you want to use the entire string) try this:
<?php
$regexp = "/^(\/\?paged)+=(\d+)+$/";

Related

preg_match / word boundery only works to a limited extent

I would like to compare a text from its textarea with a come-separated keyword list and trigger a specific action if one or more hits are found.
Unfortunately, my script only works to a limited extent and triggers my function even if a character string, e.g. B. "ee" or "work" is identified.
Example for the keyword list:
"FREE Shipping,times,50% OFF,Backpack,Marketing,working,Owner,CEO"
Example of a text from the textarea:
"it seems that the function is not working correctly"
$messageTemp = explode(",",$GLOBALS['Message']);
foreach ($messageTemp as $valueK) {
if (preg_match("~\b(.+)$valueK\b~",$GLOBALS['Keyword']) !== 0 ) {
$GLOBALS['Key'] = 1;
};
};
I'm grateful for every hint
To put an arbitrary string inside reg exp you have to escape it first. Also, I added ignore case option. And removed the (.+) part.
foreach ($messageTemp as $valueK) {
$reg ="~\b".preg_quote($valueK, '/')."\b~i";
if (preg_match($reg, $keyword) !== 0) {
$GLOBALS['Key'] = 1;
}
}

Return true/false if word in URL matches specific word

I currently use:
if(strpos($command->href,§current_view) !== false){
echo '<pre>true</pre>';
} else {
echo '<pre>false</pre>';
}
$command->href will output something like this: /path/index.php?option=com_component&view=orders Whereas
§current_view is outputting orders. These outputs are dynamically generated, but the scheme will always be the same.
What I need to do is return true/false if the words from $current_view match the view=orders in the URLs from $command->href. The issue with my code is, that it doesnt match anything.
What is the correct way to do this?
Please note that the $command->href and the whole code is inside a while function, that pass multiple URLs and this only needs to match the same ones.
Breaking it down to a simple example, using your code and variable values.
$current_view = 'orders';
$command = '/path/index.php?option=com_component&view=orders';
if(strpos($command,$current_view) !== false){
echo '<pre>true</pre>';
}
else {
echo '<pre>false</pre>';
}
The oputput is "true".
Now, go and debug the REAL values of $command->href and $current_view...
I'm pretty confident that the values are not what you think they are.
Does something like:
if(substr($command->href, strrpos($command->href, '&') + 6) == $current_view)
accomplish what you are after?
To explain, strpos get the last instance of a character in a string (& for you, since you said it always follows the scheme). Then we move over 6 characters to take "&view=" out of the string.
You should now be left with "orders" == "orders".
Or do you sometimes include some arguments after the view?
Try parsing url, extracting your view query string value and compare it to $current_view
$query= [];
parse_str(parse_url($command->href)['query'], $query);
if($current_view === $query["view"])
echo '<pre>true</pre>';
} else {
echo '<pre>false</pre>';
}

Something like SQL "LIKE" but in PHP

I have few url in my database, it goes like:
id url
1 http://test.com/embed-990.html
2. http://test2.com/embed-011.html
3. http://test3.com/embed-022.html
How I could make a simple php code if one of url doesn't exist in database, just to load another? I need to check these url by domain as well.
For example something like this:
if($data['url'] == "test.com") {
echo "my embed code number 1";
} elseif($data['url'] == "test2.com") {
echo "my another embed code";
}
You can parse the URL to get the host then compare it.
$dataurl = array('http://test.com/embed-990.html',
'http://test2.com/embed-011.html',
'http://test3.com/embed-022.html');
foreach($dataurl as $url) {
switch(parse_url($url, PHP_URL_HOST)) {
case 'test.com':
echo 'test domain';
break;
case 'test2.com':
echo 'test domain 2';
break;
default:
echo 'unknown';
break;
}
echo $url . PHP_EOL;
}
Demo: https://3v4l.org/nmukK
For the question Something like SQL “LIKE” you could use a regex in preg_match.
You can use substr_count
if (substr_count($data['url'], 'test.com') > 0) {
echo "my embed code number 1";
}
else if (substr_count($data['url'], 'test2.com') > 0) {
echo "my embed code number 2";
}
or strpos
if (strpos($data['url'],'test.com') !== false) {
echo "my embed code number 1";
}
else if (strpos($data['url'],'test2.com') !== false) {
echo "my embed code number 2";
}
or preg_match
if(preg_match('/test.com/',$data['url']))
{
echo "my embed code number 1";
}
else if(preg_match('/test2.com/',$data['url']))
{
echo "my embed code number 2";
}
You can use Regx
$domains = ['test.com', 'test1.com', 'test20.com'];
foreach( $domains as $domain ){
if(preg_match('/test([0-9]*)\.com/', $domain, $match)){
echo "my embed code number {$match[1]}\n";
}
}
Outputs:
my embed code number
my embed code number 1
my embed code number 20
you can test it here
http://sandbox.onlinephpfunctions.com/code/1d4ed1d7505a43b5a06b5ef6ef83468b20b47799
For the regx
test matches test literally
([0-9]*) - capture group, matches 0-9 none or more times
\. matches . literally
com matches com literally
One thing to note is that placing the * outside the capture group ([0-9])* will match and pass the if, but will not capture anything within the capture group. This makes sense, but its important to note because you'll get this message:
Notice: Undefined offset: 1 in [...][...] on line 6
for test.com.
If you want to match the number in embed- You can use one of these
'/test\.com\/embed-([0-9]{3})\.html/'
'/\/embed-([0-9]{3})\.html/'
'/\/embed-([0-9]{3})\./'
Depending how specific you want to be. You can play around with different Regx on this page.
https://regex101.com/r/snuqRc/1
Regular expressions are very powerful, they are meant for pattern matching, which is what you need.
Cheers.

How to select multiple URLs wiht request_uri

I'm having php script that deals with thousands of queries starting just like (i.e. http://localhost:1234/browse.php?cat=2) so I don't want to write thousands of URLs in an array to deal with if and else condition such as below,
Please guide me how can i make it possible to use "?" sign in my url to distinguish between what command to process if url contains "?" sign.
I used "/browse.php?*" in code as shown in below example but it's not working for me still...Please guide because I'm new in php and search and lot regarding this answer but unable to find a single authentic answer for it, thanks
if(in_array($_SERVER['REQUEST_URI'],array('/browse.php','/browse.php?*')))
{
echo "<Something Like this 1>";
}
elseif ($url == "")
{
echo "<Something Like this 2>";
};
in_array would only check for a full match here and is not appropriate for what you are trying to do. PHP has many String Functions you should look at.
if (strpos($_SERVER['REQUEST_URI'], '?') !== false) {
//URL has '?' mark
}
else{
//URL has no '?' mark
}
I believe you are only concerned with the cat URL search parameter? If so, you can access this parameter in your browse.php script using the $_GET array:
<?php
if (array_key_exists('cat', $_GET)) {
echo "cat parameter: {$_GET['cat']}"; // display ?cat=value
} else {
echo 'No cat URL parameter'; // ?cat was not in the URL
}
?>
http://localhost:1234/browse.php -> No cat URL parameter
http://localhost:1234/browse.php?cat=57890 -> cat parameter: 57890

Checking Users HTML form input with PHP

I am creating a web application that takes in a user input (Scientific Paper DOI) and queries a database to display a graph. I've been trying to limit the connections made to the database since its on a remote server (private DMZ with web server) by checking the user input if it matches a correct DOI.. if it doesn't then no connection to the database will be made, I hope this will help speed up the application if there are many users at once making queries.
Pseudo: All paper DOIs start with "10.1103/" because they are all physics papers. This part I have implemented correctly using substr. Next I want to check every character in the input to make sure it only consists of only these characters:
Letter
Number
"/"
"."
Example DOIs:
10.1103/RevModPhys.9.1
10.1103/RevModPhys.76.1015
10.1103/PhysRevLett.95.208304
Here is my code:
function checkDOI($doi) {
if (substr($doi, 0, 8) != "10.1103/") {
echo "Invalid DOI";
return false;
}
for ($n = 0; $n < strlen($doi)+1; $n++) {
if ( !ctype_alnum($doi[n]) && $doi[n] != "." && $doi[n] != "/") {
echo "Invalid DOI";
return false;
}
}
echo "Valid DOI";
return true;
}
if(isset($_POST['submit'])) {
$doi_input = $_POST['doi_input'];
checkDOI($doi_input);
}
I am working with PHP and javascript for the very first time, the pseudo is fairly simple but for some reason, there is something wrong with the 2nd if statement. Not sure if I can really do that. The Echos are just for tests.
Do you think doing this check for every input will slow down the application significantly? Is it worth it to limit the amount of connections to mysql?
The bottom of the code will be modified once I have this working to only query the database if checked returns true.
Thanks for the help!
to check every character in the input to make sure it only consists of only these characters
I suggest you to use preg_match.Try this:
$value="10.1103/RevModPhys.9.1";
if(preg_match("/^[a-zA-Z0-9\/.]+$/", $value)){
echo "match found";
}else{
echo "no match found";
}
Check here: Demo
For more info: preg_match
Your error is $doi[n], it is not an array and should it be the index is invalid.
So use a function like
$chars_doi = str_split($doi);
Before the loop to get an array of characters then use in your loop
$chars_doi[$n]
So you should have something like:
$chars_doi = str_split($doi);
$size = sizeof($chars_doi) - 1;
for ($n = 0; $n < $size; $n++) {
if (!ctype_alnum($chars_doi[$n]) && $chars_doi[$n] != "." && $chars_doi[$n] != "/") {
echo "Invalid DOI";
return false;
}
}
Little tip, avoid use functions such as strlen / sizeof as a loop argument or it will get called at each iteration. It is better for performance to store the value in a variable beforehand.
I would just do:
if (! preg_match ('#^10\.1103/[\p{L}\p{N}.-_]+$#', $doi)) {
... // bad
return;
}
// good
Reference:
http://www.php.net/manual/en/reference.pcre.pattern.syntax.php
http://php.net/manual/en/regexp.reference.unicode.php

Categories