View Full Version : String Manipulation in PHP
paxdev
September 7th, 2006, 11:25 AM
Hi,
I have data like
1.5oz
2.25oz
4lbs
50lbs
etc
I need only the integer part of the data to calculate the weight.
How to do it?
Thanks
bwh2
September 7th, 2006, 11:34 AM
<?php
$values = array(
'1.5oz',
'2.25oz',
'4lbs',
'50lbs'
);
foreach( $values as $value ) {
echo preg_replace( '/[A-Za-z]/', '',$value ).'<br />';
}
?>
but you will also need to grab the units to run a conversion unless your values are already in the same unit.
bwh2
September 7th, 2006, 01:16 PM
keep in mind i'm a total regex hack, but this should work:
<?php
$values = array(
'1.5oz',
'2.25oz',
'4lbs',
'50lbs',
'239874983274.2342oz'
);
foreach( $values as $value ) {
$number = preg_replace( '/[A-Za-z]/', '',$value );
$unit = preg_replace( '/[0-9.]/', '', $value );
echo "Number: ".$number."\n<br />";
echo "Unit: ".$unit."\n<br />";
echo '<br />';
}
?>
Seb Hughes
September 7th, 2006, 04:44 PM
Hey.
<?php
$values = array(
'hfhjgfj',
'dgfjdgfj',
'dgjgfdj',
'dfgjdfj',
'dfgjdgfjdgfj'
);
foreach( $values as $value ) {
$number = preg_replace( '/[A-Za-z]/', '*',$value );
echo "Number: ".$number."\n<br />";
echo '<br />';
}
?>
I have this code, I was wondering how do i get it so say the last 4 letter will appear as * and not all appear as *?
hl
September 7th, 2006, 04:46 PM
substr($string, strlen($string)-4, strlen($string)) Just delete that portion and add four asterisks.
(You might have to check that syntax.)
bwh2
September 7th, 2006, 05:06 PM
@seb:
/* fun method */
$charsToChop = 4;
$chopChar = '*';
$string = substr( $string,0,strlen($string)-$charsToChop ).str_repeat( $chopChar, $charsToChop );
/* quick and dirty method */
$string = substr($string,0,strlen($string)-4).'****';
hl
September 7th, 2006, 05:23 PM
^ Yep. You could also use arrays.
bwh2
September 7th, 2006, 05:25 PM
as the saying goes, tmtowtdi.
hl
September 7th, 2006, 05:45 PM
today mine, tommorow ours, we the damn its!
Powered by vBulletin® Version 4.1.10 Copyright © 2012 vBulletin Solutions, Inc. All rights reserved.