1

I have the following line in a php file that grabs a value and returns it as a jQuery variable:

var HeaderWrapperHeightNEW = <?php if(get_theme_mod('header_image_full_size') != '1'){ echo get_theme_mod('header_height');}?>;

My problem is that sometimes the returned result has a letter unit after it, for example 600px or 50% - I just need it to echo the number and not the unit. Is this possible to do? And how would I do it?

Sam Skirrow
  • 3,647
  • 15
  • 54
  • 101
  • 2
    http://stackoverflow.com/questions/6307827/how-to-convert-a-string-with-numbers-and-spaces-into-an-int – adeneo Nov 22 '14 at 14:18
  • http://stackoverflow.com/questions/239136/fastest-way-to-convert-string-to-integer-in-php, – Salman A Nov 22 '14 at 14:23

2 Answers2

3

You could use the PHP function floatval():

<?php
$str = '-10.5px';
$str = floatval($str);
echo $str; // -10.5
?>

You could also use type casting:

<?php
$str = '-10.5px';
$str = (float)$str;
echo $str; // -10.5
?>

Note:

  • It also handles a minus symbol and a float. '10px' would still return just 10 but is a float.
  • If only integers should be returned use $str = (int)$str; instead.
  • Nothing should precede the value. $str = 'margin: -10.5px'; would return 0 in both cases.
Martin Postma
  • 91
  • 1
  • 14
0

This will clean up all non-digits from the string:

string_with_units.replace(/[^-\d\.]/g, '');
Gonsalo Sousa
  • 495
  • 4
  • 9
  • This happens on the JavaScript side, not in PHP. In PHP, use functions like [floatval](http://php.net/manual/en/function.floatval.php) or [intval](http://php.net/manual/en/function.intval.php) to parse a float or an integer from a string. – Daniel Jan 20 '16 at 14:47