PHP building a basic calculator system from user input - php

I'd like to make a script where the user can enter a sum e.g. 4^5+(56+2)/3 or any other basic maths sum (no functions etc.) how would I go about doing this? Presumably regex. Could somebody point me in the right direction - I'm guessing this isn't going to be too easy so I'd just like some advice on where to start and I'll take it from there.

Have a look at this: http://www.webcheatsheet.com/php/regular_expressions.php
It's a good intro to Regular Expressions and how to use them in PHP.
Yes, someone can (and probably will) just give you the regex you need to work this out but it helps a lot if you understand HOW your regex works. They look scary but aren't that bad really...

this is not my code, but there is a great PHP snippet that lets you use Google Calculator to do the calculations. So you can just enter your query (ie, "7+3") using regular/FOIL notation or whatever, and it will return the result.
http://www.hawkee.com/snippet/5812/
<?php
// Google calculator
function do_calculator($query){
if (!empty($query)){
$url = "http://www.google.co.uk/search?q=".urlencode($query);
$f = array("Â", "<font size=-2> </font>", " × 10", "<sup>", "</sup>");$t = array("", "", "e", "^", "");
preg_match('/<h2 class=r style="font-size:138%"><b>(.*?)<\/b><\/h2>/', file_get_contents($url), $matches);
if (!$matches['1']){
return 'Your input could not be processed..';
} else {
return str_replace($f, $t, $matches['1']);
}
} else {
return 'You must supply a query.';
}
}
?>

The easy way to do it is with eval(). If you're accepting arbitrary input from a web form and executing in on a server, though, you MUST be careful to only accept valid expressions. Use a regex for that.

Related

How to format a UK bank sort code?

As part of a form I collect a users bank details which includes their sort code. The sort code is stored in the database as six numbers, for example 771731.
I'd prefer to store the sort code in this format (without the hyphens) as it makes it easier for me to work with in other areas of the site. I want to output the sort code in one area of the site but in the format 77-17-31 using PHP.
I have searched Google for a solution but surprisingly found very little.
This is the prefect use-case for wordwrap(), just use it like this:
$code = "771731";
echo wordwrap($code, 2, "-", TRUE);
output:
77-17-31
Just figured this out using PHP functions, thought I'd post the answer in case it helped anyone else doing a Google search...
function formatSortCode($str) {
return implode("-", str_split($str, 2));
}
echo formatSortCode('771731'); // outputs 77-17-31
I arrived here looking for a JavaScript answer not realising it was a PHP question. Tweaking #MichaelLB's answer, the JavaScript translation is
function formatSortCode(str) {
return (String(str).match(/.{1,2}/g) || []).join('-');
}
formatSortCode(123456789);
>>> "12-34-56-78-9"

PHP How do I create an if statement using only preg_match?

I am trying to append a URL if necessary, and skip over it when not necessary. The think is, I'm learning php right now and I would like to use regular expressions as much as possible. would it be possible to make this code more concise using preg_match? Example:
<?php
$facebook_url = str_replace("facebook.org","facebook.com", trim($_REQUEST['facebook_url']));
$position = strpos($facebook_url, "facebook.com");
if ($position === false) {
$facebook_url = "http://www.facebook.com/" . $facebook_url;
}
?>
But using:
if (!preg_match("/^(http:///www.facebook.com | facebook.com)/i"), $facebook_url)) {
$facebook_url = "http://www.facebook.com/" . $facebook_url;
}
I feel like that should work the way I understand php syntax, but something isn't working right. Thank you in advance.
I don't know why you would want to use regex "as much as possible" as opposed to as much as is needed, which should be very little. In your case the original code is much faster, and you can still do it with less code:
if (stripos($facebook_url, "facebook.com") === false) {
Your regex would require a space after the .com or before the facebook in the alternation. Space matters in regex.

PHP+CSS Obfuscation - PHP ord THEN PHP strrev + CSS reverse text, how to get the special chars validated backwards?

I have a been reading up on email obfuscation.
I found an interesting post entitled Best Method for Email Obfuscation? - By Jeff Starr where he describes various tests preformed over 1.5 years by Silvan Mühlemann.
According to this study, css obfustication was 100% effective throughout the 1.5-year test, despite its various downsides.
Seeing as i was playing around with this method of obfustication before, i decided to give it another go, with the addition of a php function that i came accross.
Here is the function:
// Converts email and tel into html special characters
function convert_email_adr($email)
{
$pieces = str_split(trim($email));
$new_mail = '';
foreach ($pieces as $val)
{
$new_mail .= '&#'.ord($val).';';
}
return $new_mail;
}
And here is the php using that function.
$lstEmail = convert_email_adr("{$row['email']}");
This does exactly as described, and i would assume that this would work out quite well, assuming the harvesters have not written code that identifies the string of special chars and decodes them.
So i decided, what if i combined these two methods, as in, i break the string into special chars, then use strrev on it, then use css to reverse the string... Simple...
Here is the added peice of php that reverses the actual string as seen in the page source:
$lstEmail = strrev($lstEmail);
and the css to reverse it again on the client side:
span.obfuscate { unicode-bidi:bidi-override; direction: rtl; }
And the html:
<p><span class='listHeadings'>eMail:</span> <span class='obfuscate' style='font-size:0.6em;'><a href='mailto: $lstEmail?subject=Testing 123'>$lstEmail</a></span></p>
But the problem is that the string is now in reverse and will not be validated... Here is an example:
;901#&;111#&;99#&;64#&;801#&;501#&;79#&;901#&;301#&;46#&;411#&;101#&;001#&;011#&;111#&;611#&;011#&;79#&;811#&;301#&;501#&;79#&;411#&;99#&
What happens is that the special characters are not decoded into actual characters, so all you see is the string of special character in reverse.
There is also the downside as described by Jeff Starr, that you cannot use the css method in mailto as you cannot use the span tag within the href attribute.
So now i am truly stuck at an odds of how to go about this task. I guess i might be able to live with forcing people to input my email address themselves if they would like to mail me... But, on the other hand, i am not so sure about that.
Then there comes the task of validating special characters in reverse...
Would anyone be able to provide me with any type of input or support in this regard? Also any suggestions in different, LEGITIMATE ways of going about this task would be greatly appreciated!!
I say legitimate because i plan to use these functions in one of my live projects that is a business listing website (currently using the php function above)... The last thing i want to do is start playing around and create a gap and let out a bunch of info for the spammers! I think that would be very bad for business...
As webmaster I always put my email in plain text on the contact site. Its the most comfortable solution for the visitors and it works independent if css is supported or js.
I do this with several emails since 10 years .. yes I got some spam but not that much, about 3-5 a day. I've got a good spam filter and watch over the spam once a week and delete it.
I do not use mailto because a lot of people do not have configured a local email-program and do not know what to do with the popup when clicking the mailto-link.
Just reverse it before you obfuscate it...
$email = 'blah#whatever.co.uk';
$new = convert_email_adr($email);
echo '<span style="unicode-bidi:bidi-override; direction: rtl;">'.$new.'</span>';
function convert_email_adr($email, $reverse = true, $obfuscate = true)
{
$email = trim($email);
if($reverse)
{
$email = strrev($email);
}
if($obfuscate)
{
$pieces = str_split($email);
$email = '';
foreach($pieces as $piece)
{
$email .= '&#'.ord($piece).';';
}
}
return $email;
}
Why don't you use it that way?
function convert_email_adr($email)
{
$pieces = str_split(strrev(trim($email)));
$new_mail = '';
foreach ($pieces as $val)
{
$new_mail .= '&#'.ord($val).';';
}
return $new_mail;
}
Generally, a good solution to this is to provide a layer of abstraction around the email address entirely, by which I mean instead of just the email address, providing a contact form. They fill in their info, submit it, and your server sends along the information to the proper email address.
That's not an especially scalable approach, though, generally mostly applicable to a single "contact me" situation, not a "here are our listings of companies to contact" situation, in which case obsfucation is running directly counter to your goal of making sure the customers can contact the targets with as much ease as possible. In that case you generally want to go with good spam protection.

PHP Regex problem!

I was creating a Syntax Highlighter in PHP but I was failed! You see when I was creating script comments (//) Syntax Highlighting (gray) , I was facing some problems. So I just created a shortened version of my Syntax Highlighting Function to show you all my problem. See whenever a PHP variable ,i.e., $example, is inserted in between the comment it doesn't get grayed as it should be according to my Syntax Highlighter. You see I'm using preg_replace() to achieve this. But the regex of it which I'm using currently doesn't seem to be right. I tried out almost everything that I know about it, but it doesn't work. See the demo code below.
Problem Demo Code
<?php
$str = '
<?php
//This is a php comment $test and resulted bad!
$text_cool++;
?>
';
$result = str_replace(array('<','>','/'),array('[',']','%%'),$str);
$result = preg_replace("/%%%%(.*?)(?=(\n))/","<span style=\"color:gray;\">$0</span>",$result);
$result = preg_replace("/(?<!\"|'|%%%%\w\s\t)[\$](?!\()(.*?)(?=(\W))/","<span style=\"color:green;\">$0</span>",$result);
$result = str_replace(array('[',']','%%'),array('<','>','/'),$result);
$resultArray = explode("\n",$result);
foreach ($resultArray as $i) {
echo $i.'</br>';
}
?>
Problem Demo Screen
So you see the result I want is that $test in the comment string of the 'Demo Screen' above should also be colored as gray!(See below.)
Can anyone help me solve this problem?
I'm Aware of highlight_string() function!
THANKS IN ADVANCE!
Reinventing the wheel?
highlight_string()
Also, this is why they have parsers, and regex (despite popular demand) should not be used as a parser.
I agree, that you should use existing, parsers. Every ide has a php parser, and many people have written more of them.
That said, I do think it is worth the mental exercise. So, you can replace:
$result = preg_replace("/(?<!\"|')[\$](?!\()(.*?)(?=(\W))/","<span style=\"color:green;\">$0</span>",$result);
with
//regular expression.:
//#([^(%%%%|\"|')]*)([\$](?!\()(.*?)(?=(\W)))#
//replacement text:
//$1<span style=\"color:green;\">$2</span>
$result = preg_replace("#([^(%%%%|\"|')]*)([\$](?!\()(.*?)(?=(\W)))#","$1<span style=\"color:green;\">$2</span>",$result);
Personally, I think your best bet is to use CSS selectors. Replace style=\"color:gray;\" with class="comment-text" and style=\"color:green;\" with class="variable-text" and this CSS should work for you:
.variable-text {
color: #00E;
}
.comment-text .comment-text.variable-text {
color: #DDD;
}
Insert don't use regex to parse irregular languages here
anyway, it looks like you've run into a prime example of why regular expressions are not suited for this kind of problem. You'd be better off looking into PHP's highlight_string functionality
Well, you don't seem to care that php already has a function like this.
But because of the structure of php code one cannot simply use a regex for this or walk into mordor (the latter being the easier).
You have to use a parser or you will fly over the cuckoo's nest soon.

Is there a PHP equivalent of Perl's URI::ParseSearchString?

I'm doing some work for a client that involves parsing the referrer information from Google et al to target various parts of a page to the user's search keywords.
I noticed that Perl's CPAN has a module called URI::ParseSearchString which seems to do exactly what I need. The problem is, I need to do it in PHP.
So, to avoid reinventing the wheel, does anyone know if there is a library out there for PHP that does the same / similar thing?
parse_str() is what you are looking for.
You may additionally want to use parse_url() to get the search string.
I'm the author of the module. As far as I know, I've never seen something similar for PHP. If you do come across anything, please do let me know.
That being said, I cannot image this being very hard to port to PHP and I can have an attempt at it if you dont find anything similar out there.
Spiros
Maybe this is too inefficient or the http_referer isn't showing the full uri ...
function parse_uri($uri) {
if (substr_count('?', $uri) > 0) {
$queryString = explode('?', $uri);
return parse_str($queryString[1]);
} else {
return parse_str($uri);
}
}
if (isset($_SERVER['HTTP_REFERER'])) {
print_r(parse_uri($_SERVER['HTTP_REFERER']));
}

Categories