Can anyone help me figure out how to search a URL and print a class based on its result for example:
http://www.?.com/garden-design.html
What i am trying to achieve is using a switch using PHP mathcing a term of say "garden" after the first trailing slash then it would print a class. If it matched construction it would print a different class. There are only three so i know which words to search for. This doesnt have to be dynamic.
Any help would be appreciated.
If it does not have to be dynamic, you could do it like this:
switch(true)
{
case stripos($_SERVER['REQUEST_URI'], 'garden'):
return 'garden';
break;
case stripos($_SERVER['REQUEST_URI'], 'construction'):
return 'construction';
break;
default:
return 'default';
break;
}
The above is quite explicit. A more compact solution could be
function getCategory($categories)
{
foreach($catgories as $category) {
if stripos($_SERVER['REQUEST_URI'], $category) {
return $category;
}
}
}
$categories = array('garden', 'construction', 'indoor');
echo getCategory($categories);
This will not give you the first word after /, but just check if one of your keywords exists in the requested URI and return it.
You could also use parse_url to split the URI into it's components and work with String functions on the path component, e.g.
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
In www.example.com/garden-design.html?foo=bar, this would give you just the part garden-design.html. In your scenario you'd probably still do the stripos on it then, so you can just as well do it directly on the URL instead of parsing it.
I'd have thought that making use of parse_url would probably be a good starting point - you could then explode the path component and then do simply strpos comparisons against the three strings you're looking for, if a simple switch statement isn't sufficient. (Be sure to check for !== false if you go down the strpos route.)
This would potentially be faster than a regex based solution.
You can try a regular expression:
/http://www..+.com/(garden|construction|indoor)(-design)?.html/
then $1 would give you garden, construction or indoor as string.
you can also use (.+) to collect any string at that spot.
Update made "-design" optional.
Take a look at the php function strpos(). With it you could do something like:
$url = "http://www.nothing.com/garden-design.html";
if (strpos($url, "/garden-design.html"))
doSomething();
else if (strpos($url, "/construction-design.html"))
doSomethingElse();
else if (strpos($url, "/indoor-design.html"))
doSomethingElseInstead();
String matching is generally quicker and more efficient than regular expressions.
Related
I am using stripos to modify an active navigation class,
<?php if (stripos($_SERVER['REQUEST_URI'],'/members/login') !== false) {echo 'class="active"';} ?>
It works like a charm. However I need to add another REQUEST_URI to check in the string and cannot figure out how to properly format the code.
I have tried:
, '/members/login | /members/members'
and others without success.
You'll just have to do it twice:
if(
stripos($_SERVER['REQUEST_URI'],'/members/login') === 0
||
stripos($_SERVER['REQUEST_URI'],'/members/members') === 0){ ...
Note that I switched to ===0 as I presume you wouldn't want '/someotherpartofyoursite/members/members' to match presumably. If you want it in 1 call, you can use regular expressions (see preg_match()), but this is fast & clear enough in my opinion.
If the list becomes longer, it depends on whether these are the whole paths, and if they are, something like this could be more suitable:
$urls = array('/members/login','/members/members');
if(in_array(parse_url($_SERVER['HTTP_REQUEST_URI'], PHP_URL_PATH),$urls)){....
... but not knowing your url scheme that's a guess.
You can do that in single call to preg_match as well like this:
if (preg_match('#/members/(?:login|members)#i', $_SERVER['REQUEST_URI'])) {
// matched
}
My latest issue involves trying to find "http://" in a variable. This variable contains the contents of a comments section on a clients website. I have seen all kinds of answers but none of them seem to work. I looked at a few other posts on here and I have yet to get the best answer. Here is what I have so far:
if(strpos($comments, 'http://') == true) {
// Does stuff here
}
I noticed other people use preg_match and some said to do it in an array. I am getting confused, too many options. Just kidding. I would like some clarification though and any advice would be greatly appreciated.
You'll need to say:
if(strpos($comments, 'http://') !== false) {
...since it can return 0 (which is falsey) if http:// is at the beginning of the string.
NOTE: This will only find the first occurrence of http:// in the string.
Take a close look at the reference: http://php.net/manual/en/function.strpos.php
You need to change code like that:
if(strpos($comments, 'http://') === false) {
//no link
}
because strpos return integer which is position your string.
Example:
full string: "http://stackoverflow.com hello"
you finding: "http"
Naturally it return 0.
But
full string: "ahttp://stackoverflow.com"
you finding: "http"
it return 1.
So you must use === operator to check is really 'boolean false'.
If you try to check with == operator, you maybe get fail because it get 0 as false.
more detail: http://php.net/strpos
I found this was a better match: (recommended by phpstorm ide)
if(str_contains($e, '1062 Duplicate entry')) {
}
Is there a shorter way of writing this (without using regex or string-matching functions)?
if($page=='page1.php' || $page=='page2.php' || $page=='page3.php' || $page=='page4.php'){ do something...}
I'm looking for something like:
if($page==('page1.php', 'page2.php', 'page3.php', 'page4.php')){do something...}
but I know that isn't correct. Any suggestions?
Try in_array:
if (in_array($page, array('page1.php', 'page2.php', 'page3.php'))) { ... }
http://php.net/manual/en/function.in-array.php
Use switch, more readable than a complex if condition
switch ($page){
case 'page1.php':
case 'page2.php':
case 'page3.php':
case 'page4.php':
// do something
break;
default:
//else
}
To have an answer that is not same old same old:
if (preg_match('"^page[1-4]\.php$"', $page)) {
Now this makes sense for your synthetic example, and if you really have ranges of something to test against, or some other structure to go by. Mostly it just happens to be compacter then.
I think one possible solutions is writing function that as arguments takes page1.php, page2.php etc. and return true if statement is correct.
UPDATE
Sorry for the brain dead answer .. missed the first line. as stated above you could build an array of pages and user in_array()
$pagelist = array('page1.php','page2.php','page3.php','page4.php','page5.php')
if (in_array($page,$pagelist)) {
//do something
}
it's a bit more elegant and definately cleans up the if statement, but doesn't do much to reduce the code. the only benefit i can think is that you could build the $pagelist array from an external source and using it might be more efficient?
This is an easy one. There seem to be plenty of solutions to determine if a URL contains a specific key or value, but strangely I can't find a solution for determining if URL does or does not have a query at all.
Using PHP, I simply want to check to see if the current URL has a query string. For example: http://abc.com/xyz/?key=value VS. http://abc.com/xyz/.
For any URL as a string:
if (parse_url($url, PHP_URL_QUERY))
http://php.net/parse_url
If it's for the URL of the current request, simply:
if ($_GET)
The easiest way is probably to check to see if the $_GET[] contains anything at all. This can be done with the empty() function as follows:
if(empty($_GET)) {
//No variables are specified in the URL.
//Do stuff accordingly
echo "No variables specified in URL...";
} else {
//Variables are present. Do stuff:
echo "Hey! Here are all the variables in the URL!\n";
print_r($_GET);
}
parse_url seems like the logical choice in most cases. However I can't think of a case where '?' in a URL would not denote the start of a query string so for a (very minor) performance increase you could go with
return strpos($url, '?') !== false;
Over 1,000,000 iterations the average time for strpos was about 1.6 seconds vs 1.8 for parse_url. That being said, unless your application is checking millions of URLs for query strings I'd go for parse_url.
Like this:
if (isset($_SERVER['QUERY_STRING'])) {
}
I have an SQLITE Database's File which in one of the table columns there is some simple Regular Expressions.
These Expressions are something like /foo(.?) or /foo/bar/(.?) and so on...
Well, when we try to match some text against a Regular Pattern, in PHP, we do:
preg_match( $pattern, $target, $matches )
Replacing the variables with the content, obviously.
What I would like to do is send ANY STRING as value of a WHERE Clause and, when searching the SQLITE Database's File, use each of the stored Regular Expressions to match a pattern in the given string.
I think that using PHP's sqlite_create_function() I can create some kind of routine to do this, but I don't know exactly how, since is the first time I develop using SQLITE.
If interest, it's part of an MVC Routing of a Framework I'm developing.
Thank you very much, in advance.
You can use SQLiteDatabase::createFunction documentation here or PDO::sqliteCreateFunction documentation here
I did something like this:
<?php
function _sqliteRegexp($string, $pattern) {
if(preg_match('/^'.$pattern.'$/i', $string)) {
return true;
}
return false;
}
$PDO->sqliteCreateFunction('regexp', '_sqliteRegexp', 2);
?>
Use:
SELECT route FROM routes WHERE pattern REGEXP 'your/url/string' LIMIT 1
Is this what you are looking for?
e.g. SELECT * FROM `my_table` WHERE `my_column` REGEXP "\/foo(.?)"