Php code to check the end of a string/integer ?

Jangga

Junior Member
Joined
Aug 8, 2016
Messages
196
Reaction score
11
Pls, I'm still stuck on this. I don't know how to check the last two numbers in my string if they end with two zeros. I was using strstr() but it wasn't it. I know jS could have been more appropriate but, I'm not good with jS. So, I'm opting for php

The variable is

$price = $_POST["pricetag"];

The user is to input a value & I want to check if it contains two zeros at the end cos that's what I want and if no two zeros, it should show error. But, how do I set the pointer to check the last two zeros in their price tags?
 
Oh man..… I was hoping to get a quick fix. Seems I'll be reading a lot on the link then.... Thanks
 
You can use preg_match function to test for regular expressions:
PHP:
$string = '9.9900';

$result = preg_match('/.+0{2}$/', $string);

if ($result === 1) {
  
    echo "String ends with 00";  

} else if ($result === 0) {

    echo "String doesn't end with 00";  

}

This regular expression is a little broad and will match any kind of characters (letters/symbols/numbers) up until the last two characters that need to be two zeroes.
If the string is formed only by digits you can change it to: '/\d+0{2}$/'

If you need a more precise regular expression please provide more info about how your string is formed or some examples. :)
 
Last edited:
Hi,

Do you want to find and add two decimals after the decimal point if there are no decimals like a price value (25.00).

echo number_format($num, 2);

The above mentioned function will add 2 decimals, and avoid more decimal values after the decimal points if the values has more decimals after the decimal points.

just you would like to check the value has two 0's at the end of the value without any decimals.

use substr function.
 
Last edited:
You can use preg_match function to test for regular expressions:
PHP:
$string = '9.9900';

$result = preg_match('/.+0{2}$/', $string);

if ($result === 1) {
 
    echo "String ends with 00"; 

} else if ($result === 0) {

    echo "String doesn't end with 00"; 

}

Thank you very much for this post. This actually helped me figure out an issue I've been having, but haven't taken the time to tackle. Thanks for helping Jangga and myself!
 
  • Like
Reactions: Mex
Back
Top