Page 1 of 1

Strip off "%" from a string

Posted: Mon Sep 17, 2007 4:18 pm
by tomcatf14

Code: Select all

$variable1 = 100%
How do i strip off the % from the variable so that i can get the integer only?

Posted: Mon Sep 17, 2007 4:29 pm
by John Cartwright

Code: Select all

$variable1 = trim($variable1, '%');
:wink:

Posted: Mon Sep 17, 2007 5:58 pm
by tomcatf14
feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]


I have a little bit of problem here

Code: Select all

$score1file = "../data/df/score1";
$score1open = fopen($score1file, 'r');
$score1 = fread($score1open, filesize($score1file));
fclose($score1open);

if (trim($dfsplitdata[4], '%') >= $score1 ) {
....condition
}
$score1 = 80
This code doesn't work well as one of the splitdata[4] in a string but it still run the condition. How to i make the if condition to only execute if it is a number. Also, how do i declare $score1 as a number.


feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]

Posted: Mon Sep 17, 2007 6:02 pm
by pickle
1) Please use

Code: Select all

 tags, not [syntax=php]tags, when posting PHP code.
2) PHP is lazy typed.  You don't need to set it as a number.  However, you can try [b](int)$score1[/b] if you think it'll help.
3) You first sentence doesn't make sense to me.

Posted: Mon Sep 17, 2007 6:18 pm
by tomcatf14
Putting int() solved the problem. Initially, i thought the syntax should be int($score1). Thanks.

Let me clarify on the first sentence

$dfsplitdata[4] = it may contain string such as (abcde) or number only (after stripped off the %). Previous, before declaring $score1 as integer, (abcde) met the condition of "(trim($dfsplitdata[4], '%') >= $score1 )" which doesn't make sense because it would be "abcde >= 80". String > number. I might need some explanation on this coz i don't know what explanation on this, it might be the ASCII number count or etc. Anybody want to explain?

Posted: Tue Sep 18, 2007 10:17 am
by pickle
You could use the is_numeric() function as well in your if() clause

Posted: Tue Sep 18, 2007 4:17 pm
by nhammond
if you are always going to have that same pattern of ###% then you can just use php's str_replace function
mixed str_replace ( mixed $search, mixed $replace, mixed $subject [, int &$count] )

basically

Code: Select all

$clean_string = str_replace("%","",$my_string_to_search_through);