I have the following problem. I need to validate and possibly extract currency from a value that I have received. The trouble starts with the fact that the value can be received in any encoding. Additionally to make things worse I can receive a lot of different values that should be considered correct. Let me give an example
$ 123,123,233.00
123,123.99
123.123.123,99
123.123.123 $
All of these are correct.
What I've tried is adding three arrays:
1. Chars (",","."," ")
2. Digits(0-9)
3. Currency Signs($,€...)
Trouble started when the data came in UTF-8 and I can no longer perform search digit by digit on the value I've received as in UTF-8 Currency signs are multibyte.
Question is what to do !?
I've tried the following thing.
Search for a currency sign. Then replace it with nothing. For some unknown reason PHP only replaces the second byte of the multibyte representation of the currency sign and there is a mysterious sign in the string that fails the whole check.
Any ideas are welcomed.
Datelligent idea may actually be a good simple solution: you could replace every non numerical character except the ones useful for puntuaction, with this regex \D*(?!\d{1,2}[\D$]):
$price=preg_replace('\D*(?!\d{1,2}[\D$])', '', $price);
It would transform 1233,234 234.23 into 1233234234.23.
Careful though, stuff like 123,2 34,234 would end up 123,2 34234. It does assume that punctuation followed by three or more digits isn't relevant, doesn't account for potential typos, will delete the currency symbol, etc... but it may be relevant to the scope of your issue.
Try this:
$price=$_POST['price'];
$price=preg_replace('/[^0-9]/', '', $price);
This way PHP will remove all characters and give you a string containing only numbers, which for handling prices is perfect.
If decimals are needed then modify the RegEx to get them:
$price=preg_replace('[0-9]+(\.[0-9][0-9]?)?', '', $price);
Related
My website form is getting hammered with spam. I have noticed in the "Phone" field the spam bots always insert text rather that a number so I would like to add an if statement to the php mailer blocking the email if the phone field doesn't contain any of the following:
1) I want users to be able to leave the field blank, so empty field must be accepted.
2) Must contain "numbers" or "plus sign" or "spaces"
How would I write this in PHP?
Any help is appreciated
EDIT: Just though lol it would be much easier to just check if the field contains alphabetical characters. How would I do this?
EDIT2: Sorted. I used "if (ctype_alpha ($phone) !== false)"
Regular expressions are probably the best way, although not necessarily the easiest to understand at first. But regular expressions are definitely a good thing to learn if you are not familiar with them. My favorite introduction is this site: http://www.zytrax.com/tech/web/regex.htm And this is a good site for interactively building a regex and seeing how it works in realtime: http://www.regexr.com/ I'm sure there are plenty of other similar sites but those are the two I always go back to.
If you search around for a regular expression solution you will find countless possibilities and variations. My personal advice is to keep it simple. I would start with considering how you store the phone number data. I usually just keep the numbers, so I would simplify it by first removing those "allowed" characters and then checking if what's left over is just numbers.
$phone = str_replace(Array('+', ' ', '(', ')'), '', $phone);
That will replace all pluses, spaces, and parentheses with an empty string (i.e. remove them). Then you can check if the string is numeric, and if it is store it, otherwise print/return an error.
if (!is_numeric($phone))
// stop processing and output an error
First of all You must use some spamblock for example: token, honey pot, captcha etc.
In my country mobile or local phone number contains only 9digits without country code which is +XX. So i create INT(10) field in db. After submit form remove everything without digits.
For example:
$phoneNumber = (int) substr( preg_replace( '#[^\d]+#', '', $_POST['phone_numer'] ), 0, 9 );
In many project allways works.
my code is not working ? and i dont want to use str_replace , for there maybe more slashes than 3 to be replaced. how can i do the job using preg_replace?
my code here like this:
<?php
$str='<li>
<span class=\"highlight\">Color</span>
Can\\\'t find the exact color shown on the model pictures? Just leave a message (eg: color as shown in the first picture...) when you place order.
Please note that colors on your computer monitor may differ slightly from actual product colors depending on your monitor settings.
</li>';
$str=preg_replace("#\\+#","\\",$str);
echo $str;
There is merit in the other answers, but to me it looks like what you're actually trying to accomplish is something very different. In the php code \\\' is not three slashes followed by an apostrophe, it's one escaped slash followed by an escaped apostrophe, and in the rendered output, that's exactly what you see—a slash followed by an apostrophe (with no need to escape them in the rendered html). It's important to realize that the escape character is not actually part of the string; it's merely a way to help you represent a character that normally has very different meaning in within php—in this case, an apostrophe normally terminates a string literal. What looks like 4 characters in php is actually only 2 characters in the string.
If this is the extent of your code, there's no need for string manipulation or regular expressions. What you actually need is just this:
<?php
$str='<li>
<span class="highlight">Color</span>
Can\'t find the exact color shown on the model pictures? Just leave a message (eg: color as shown in the first picture...) when you place order.
Please note that colors on your computer monitor may differ slightly from actual product colors depending on your monitor settings.
</li>';
echo $str;
?>
Only one escape character is needed here for the apostrophe, and in the rendered HTML you will see no slashes at all.
Further Reading:
Escape sequences
The root of this problem is actually in how it was written into your database and likely to be caused by magic_quotes_gpc; this was used in older versions and a really bad idea.
The best fix
This requires a few steps:
Fix the script that puts the HTML inside your database by disabling magic_quotes_gpc.
Write a script that reads all existing database entries, applies stripslashes() and saves the changes.
Fix the presentation part (though, that may need no changes at all.
Alternative patch
Use stripslashes() before you present the HTML.
use this pattern
preg_replace('#\\+#', '\\', $text);
This replaces two or more \ symbols preceding an ' symbol with \'
$theConvertedString = preg_replace("/\\{2,}'/", "\'", $theSourceString);
Ideally, you shouldn't have code causing this issue in the first place so I would have a look at why you have \\' in your code to begin with. If you've manually put it in your variables, take it out. Often, this also happens with multiple calls to addslashes() or mysql_real_escape_string() or a cheap hosting providers' automatic transformation of all POST request variables to escape slashes, combined with your server side PHP code to do the same.
I have a large string variable that is assigned from a database column of type "Text" with Collation latin_swedish_ci.
Because it is in ASCII, I need to replace all non UTF-8 characters before I can put variable into my PDF generation script.
As we all know, the standards used by PDF are evil. If I use plain ASCII input it will go insane and cause a rip in space-time.
So in order to prevent anymore damage to our universe, I need help figuring out why this str_replace() function is only replacing one of a character type and ignoring any repeats of this character
Here is my code:
$tc = str_replace (array("\n", "£", "&"), array("<br/>", "£", "&"), $tc);
Input:
Terms & Conditions: Mandatory charge of £10 for cancellations.
VAT E&EO
Output:
Terms & Conditions: Mandatory charge of £10 for cancellations.
VAT E&EO
As you can see in the output on the second line the str_replace() does not change the ampersand character.
I wonder if this is because its over two lines or something like that.
So any idea how to get the function to work as I want it to, otherwise well your going to wake up with many Micro Blackholes vanishing your bowl of cereal tomorrow.
It looks like what you are trying to achieve could be done using these 2 functions:
nl2br(htmlentities($tc));
The benefit being that if your $tc variables gets any more HTML entities in the future, you won't have to fiddle with your str_replace().
Original format:
<a href="http://www.example.com/t434234.html" ...>
1. I need to fetch all URLs of this format:
http://www.example.com/t[ANY CHARACTER].html
ANY CHARACTER is where value changes from URL to another. The rest are fixed.
Here is my attempt:
preg_match("#http:\/\/www\.aqarcity\.com\/t[a-zA-Z0-9_]\.html#", $page, $urls);
I get empty results. I don't know where i went wrong...
The problem appears to be that [a-zA-Z0-9_] will only match exactly one character. If you want to match zero or more characters, use [a-zA-Z0-9_]*. For one or more, use [a-zA-Z0-9_]+. For exactly six characters, use [a-zA-Z0-9_]{6}. For e.g. one to six characters, use [a-zA-Z0-9_]{1,6}.
Also note that, since you're using # as the delimiter, you don't need to escape the / characters. As far as I know this will not make your code misbehave, but it'll be easier to read if you remove the backslashes before the slashes.
Finally, please realize that regular expressions are a rather dangerous way to work with HTML. In this case, you may pick up matching URLs from comments, Javascript code, and other things that aren't links. It is literally impossible to correctly parse HTML with unaugmented regular expressions—they don't have the expressive power necessary to do so. I don't know what sorts of HTML parsers are available for PHP, but you may want to look into them.
I have an input for users where they are supposed to enter their phone number. The problem is that some people write their phone number with hyphens and spaces in them. I want to put the input trough a filter to remove such things and store only digits in my database.
I figured that I could do some str_replace() for the whitespaces and special chars.
However I think that a better approach would be to pick out just the digits instead of removing everything else. I think that I have heard the term "whitelisting" about this.
Could you please point me in the direction of solving this in PHP?
Example: I want the input "0333 452-123-4" to result in "03334521234"
Thanks!
This is a non-trivial problem because there are lots of colloquialisms and regional differences. Please refer to What is the best way for converting phone numbers into international format (E.164) using Java? It's Java but the same rules apply.
I would say that unless you need something more fully-featured, keep it simple. Create a list of valid regular expressions and check the input against each until you find a match.
If you want it really simple, simply remove non-digits:
$phone = preg_replace('![^\d]+!', '', $phone);
By the way, just picking out the digits is, by definition, the same as removing everything else. If you mean something different you may want to rephrase that.
$number = filter_var(str_replace(array("+","-"), '', $number), FILTER_SANITIZE_NUMBER_INT);
Filter_Var removes everything but pluses and minuses, and str_replace gets rid of those.
or you could use preg_replace
$number = preg_replace('/[^0-9]/', '', $number);
You could do it two ways. Iterate through each index in the string, and run is_numeric() on it, or you could use a regular expression on the string.
On the client side I do recommand using some formating that you design when creating a form. This is good for zip or telephone fields. Take a look at this jquery plugin for a reference. It will much easy later on the server side.