I'm creating a simple PHP routing class.
I want to check REQUEST_URI for RegEx patterns, for example:
foreach($routes AS $pattern) {
$captures = NULL;
if(preg_match($uri, $pattern, $captures)) { /* do something */ }
}
But if I'll have too much routes this code will check them too long.
Is there more fast method for doing this?
Thank you.
No, you have to loop over them.
The bigger question is why do you think "the code will check them too long"? Have you tried it? How many routes do you have? This sounds like premature optimization, where you're concerned about making things faster when you actually have no idea if it's not fast enough.
Try it with a lot of patterns and see how long it actually takes. If it's a problem, then it's worth pursuing. Otherwise, it's just a waste of your time.
Related
I want to pass this input
$string = "AL & JRL buSineSS CENTRE is the best";
Expected Result:
AL & JRL Business Centre Is The Best
I have tried the code below but it converts everything.
mb_convert_case($string, MB_CASE_TITLE, "UTF-8");
So I take it you just want potential acronyms to be ignored, correct? Well, there are a few thoughts. First, you could make a script that ignores anything with 3 or less letters. That's not a great solution, in my opinion. What about "it", "the", etc.? The second is using a dictionary of known words to run ucwords() on. Yuck - that'd be incredibly taxing for such a seemingly simple task!
I'd recommend simply ignoring anything that is all-caps. This way, no matter what the acronym is (or the length), it'll ignore it. Something like this may suffice:
$phrase = "Hello this is a TeSt pHrAse, to be tested ASAP. Thanks.";
$chunks = explode(" ", $phrase);
$result = "";
foreach($chunks as $chunk){
if(!ctype_upper($chunk)) {
$result .= ucwords($chunk) . " ";
} else {
$result .= $chunk . " ";
}
}
$result = rtrim($result);
Result:
Hello This Is A Test Phrase, To Be Tested ASAP. Thanks.
This isn't the most elegant solution, this is just something I've kind of thought about since reading your question. However, if you know your acronyms will be capitalized, this will skip them entirely and only title-case your actual words.
Caveats
The example provided above will not work with an acronym joined to a word by a dash, underscore, etc. This only works on spacing. You can easily tweak the above to your needs, and make it a little more intelligent. However, I wanted to be very clear that this may not fulfill all needs!
Also, this example will come up short in your example phrase. Unfortunately, unless you use a dictionary or count string lengths, this is the closest you'll get. This solution is minimal work for a great deal of functionality. Of course, a dictionary with comparisons would work great (either a dictionary of acronyms or words, either way) - but even then it would be very difficult to keep up to date. Names will throw off a dictionary of words safe to change to title-case. Less commonly used acronyms surely won't be in a dictionary of acronyms. There are endless caveats to all solutions unfortunately. Choose what's best for you.
Hope this helps. If you have any further questions please comment and I'll try the best I can to help.
Randomness
One last thing. I used ucwords(). Feel free to use whatever you want. I'm sure you already know the difference, but check this out:
Best function for Title capitlization?
Always good to know exactly what tool is best for the job. Again, I'm sure you know your own needs and I'm sure you chose the right tool. Just thought it was an interesting read that could help anyone stumbling upon this.
Final Thoughts
You could use a combination of the above examples to custom tailor your own solution. Often it's very satisfactory to combine methods, thus reducing the downsides of each method.
Hope this helps, best of luck to you!
I am penetration testing a web application and I need to concatenate two functions in one URL. (Yes, I already checked this one and this one)
I am going to take the exact same code, because I did not understand why there is no proper answer to a legit question like this one. (psst, it's not about a backdoor or something)
<?php
if(isset($_GET['function'])){
$_GET['function']();
}
?>
Is there any possibility to create something like this?
http://localhost/?function=shell_exec('ls') AND phpinfo
Thank you for your help and I hope this time someone will take a legit question seriously instead of downvoting it to hell for no logical reason.
There's two problems here, I'll answer the question first.
Why not make it an array?
Url:
http://localhost/?function[]=phpinfo&function[]=bob
Code:
$functions = (array)$_GET['function'];
foreach($functions as $function) {
$function();
}
The second problem is you aren't easily going to be able to pass in parameters as you have it above. You might need to do a little bit of regex first, but then you're on thin ice.
This is a huge guess, but something like:
$matches = [];
preg_match('/(\w+)\(('?(\w+)'?,?)+\)/', $functions, $matches);
You should then be able extract the function name and parameters (as long as they're strings) and call the function with the parameters. But that regex is obviously dodgy as anything :/
That looks extremely dangerous. You can pass a string separated with a semicolon for each function, like this
:
http://localhost/?function=shell_exec('ls');phpinfo
So your actual code would become:
if(isset($_GET['function'])){
$functions = explode(';',$_GET['function']);
foreach($functions as $function){
$function();
}
}
You may also use the eval function:
http://localhost/?function=?eval=shell_exec('ls');phpinfo();
followed by eval($_GET['eval']);, as suggested in the comments below.
I need to find 1 word from a string, like:
$row['keyword'] = "hello my name is jon";
If the word "text" matches to one word from $row['keyword'] so do something..
I try this, but i think there is a better way:
foreach($rows as $row)
{
if (strpos($row['keyword'],"text") !== false) {
// do something
}
}
I think the code you've provided looks fine, it's probably the best solution for the job you want to do already. The only question I have regarding it is "Do you want to run whatever the do-something code is for every haystack that contains the needle, or just for the first one you find?". If it's the latter, then you should add a break; after the do-something code.
If you're trying to performance-tune your code, then this really isn't the sort of thing you need to worry about. Any change you make to the code as is would be a micro-optimization at best and would have negligible impact for a disproportionate amount of work. If your code performs okay then don't worry about it. If it is suffering performance issues then you need to investigate exactly where the bottlenecks are and why they're occurring, and optimizing those parts of your script. When optimizing it's important to find where you'll gain the maximum benefit from the effort needed.
The biggest and best optimization choice you can make is selecting the right algorithm for what you want to do, everything else is implementation details.
there are many alternatives and ways but depend on your requirement. You can check this link http://us2.php.net/strstr and "See Also" section. Moreover, You can simplified your code rather than using array and loop. Please see the following:
$str = 'hello my name is jon';
if(strpos($str, 'text')!='')
echo "do something";
else
echo "do something";
I was reading sourses of OpenCart and phpBB engines and noticed that there are lot of strings (sometimes full screen listings) with repeated code, which differs only in one parameter. Such as:
$this->data['button_cart'] = $this->language->get('button_cart');
$this->data['button_wishlist'] = $this->language->get('button_wishlist');
$this->data['button_compare'] = $this->language->get('button_compare');
$this->data['button_continue'] = $this->language->get('button_continue');
I am thinking about using function for generating code using paterns, and then eval() it.
Some such function:
function CodeGenerator($patern, $placements_arr){
$echo_str = '';
foreach($placements_arr as $placement){
$echo_str .= str_replace('=PATERN=', $placement, $patern);
}
if(substr($echo_str, -1)!==';'){
$echo_str .= ';'; # for correct eval() working
}
return $echo_str;
}
And then for large repeated blocks of code with same patern:
$patern = "$this->data['=PATERN='] = $this->language->get('=PATERN=');";
$placements_arr = array('button_cart', 'button_wishlist', 'button_compare', 'button_continue');
$echo_str = CodeGenerator($patern, $placements_arr);
eval($echo_str);
I want to understand PRO and CONTRA of such design, because I am thinking about using such design in my future development.
The only problem I see here now - a bit more slow execution. Any others?
Well for the block of code you have shown you could rewrite it like this
$params = array('button_cart', 'button_wishlist', 'button_compare', 'button_continue');
foreach($params as $param)
$this->data[$param] = $this->language->get($param);
You are writing out the parameters anyways, so I cannot see one benefit to your code over something like what I have shown above. Plus this is only 3 lines of code vs 11 of yours, and mine is instantly readable
in 99.9% of the code you write, you can write it without eval. There are some corner cases where eval makes sense, but in my 5 years of coding php so far I have used it maybe one or 2 times, and if I went back to the code I could probably rewrite it so It didn't.
If I had to maintain a project with code that you wrote, I would be tearing my hair out. Just look at what OpenCart wrote, and look at what you wrote. Which one is easier to understand? I actually have to look at your code a few times to understand what it is doing, I can skim over the OpenCart code and instantly understand what is happening.
Maintainability - if that's a word - might be a small concern. I would despise such a construct because it seems unnecessarily complex. I have inherited many - a - poorly designed php sites working as a web developer and in just about zero cases can I recall it being considered a nuisance to have to spool through a list of var assignments like above. However, I would become infuriated by having to deal with weird lazy functions that attempt to escape the banalities of repetitive typing.
In the end you're talking about fractions of a second for processing so that's hardly an argument for doing something like this. And if the microseconds are a concern, use a caching mechanism to write to flat text and wipe out all redundant processing all together.
Hey, my 2 cents. If it's your project and you don't expect anyone else to maintain it then knock yourself out.
I'm creating a very simple PHP templating system for a custom CMS/news system. Each article has the intro and the full content (if applicable). I want to have a conditional of the form:
{continue}click to continue{/continue}
So if it's possible to continue, the text "click to continue" will display, otherwise, don't display this whole string. So far, it works like this: if we can continue, remove the {continue} tags; otherwise, remove the whole thing.
I'm currently using preg_match_all to match the string in the second case. What is the best function for removing the matched text? A simple str_replace, or something else?
Or is there a better way to implement this overall?
Why not use preg_replace_callback?
Specifically:
preg_replace_callback('!\{continue\}(.*)\{/continue\}!Us', 'replace_continue', $html);
function replace_continue($matches) {
if (/* can continue */) {
return $matches[1];
} else {
return '';
}
}
I find preg_replace_callback to be incredibly useful.
Sorry I know people have been ridiculing this kind of answer, but just use Smarty. Its simple, stable, clever, free, small and cheap. Spend an hour learning how to use it and you will never look back.
Go to www.smarty.net
For PHP templating systems the proper way is to parse the template (using state machine or at least preg_split), generate PHP code from it, and then use that PHP code only. Then you'll be able to use normal if for conditional expressions.
Regular expressions aren't good idea for implementing templates. It will be PITA to handle nesting and enforce proper syntax beyond basic cases. Performance will be very poor (you have to be careful not to create backtracking expression and even then you'll end up scanning and copying KBs of templates several times).