I am using this function to convert square meters to square foot.
$sinput = rtrim(get_field('fl_area'), ", \t\n");
if(trim($sinput) == "0"){echo ' ' ;} else {$soutput = metersToSquareFeet($sinput); echo $soutput . ' sq. m (' . number_format($sinput ) . ' sq. f)' ;}
function metersToSquareFeet($meters, $echo = true)
{
$m = $meters;
$valInFeet = $m*10.7639;
$valFeet = (int)$valInFeet;
if($echo == true)
{
echo $valFeet;
} else {
return $valFeet;
}
}
Problem I have is with line:
rtrim(get_field('fl_area'), ", \t\n");
The user enters the number in the format 3,246 and i want to convert this to 3246 for my function to work.
Of course I could also modify the function somehow and not use rtrim in the first place
rtrim only removes characters from the end of the string, not the middle. Use preg_replace:
$sinput = preg_replace('/[,\s]+/g', '', get_field('fl_area'));
You have a few options but probably your easiest one is to remove all non-numeric characters.
Not sure what your get_field does but assuming it just gets the field from the Input you could use regex like so.
$sinput = preg_replace( '/[^0-9]/', '', $get_field('fl_area') );
Also see: PHP regular expression - filter number only
You can use str_replace() to remove all occurrences of commas and spaces from the string:
$m = str_replace(array(',',' '), '', $m);
Or even strtr():
$m = strtr($m, array(',' => '', ' ' => ''));
This is likely to be faster than regular expessions. However, if the number of function calls are minimal, the difference wouldn’t be noticeable.
Try this:
str_replace(array(',',' '), '', get_field('fl_area'));
Related
I have searched everywhere but can't find a solution that works for me.
I have the following:
$bedroom_array = array($studio, $one_bed, $two_bed, $three_bed, $four_bed);
For this example lets say:
$studio = '1';
$one_bed = '3';
$two_bed = '3';
I then use the implode function to put a comma in between all the values:
$bedroom_list = implode(", ", array_filter($bedroom_array));
echo $bedroom_list;
This then outputs:
1, 2, 3
What I want to do is find the last comma in the string and replace it with an &, so it would read:
1, 2 & 3
The string will not always be this long, it can be shorter or longer, e.g. 1, 2, 3, 4 and so on. I have looked into using substr but am not sure if this will work for what I need?
Pop off the last element, implode the rest together then stick the last one back on.
$bedroom_array = array('studio', 'one_bed', 'two_bed', 'three_bed', 'four_bed');
$last = array_pop($bedroom_array);
$string = count($bedroom_array) ? implode(", ", $bedroom_array) . " & " . $last : $last;
Convert & to the entity & if necessary.
if you have comma separated list of words you may use:
$keyword = "hello, sadasd, sdfgdsfg,sadfsdafsfd, ssdf, sdgdfg";
$keyword = preg_replace('/,([^,]*)$/', ' & \1', $keyword);
echo $keyword;
it will output:
hello, sadasd, sdfgdsfg,sadfsdafsfd, ssdf & sdgdfg
A one-liner alternative, that will work for any size array ($b = $bedroom_array):
echo count($b) <= 1 ? reset($b) : join(', ', array_slice($b, 0, -1)) . " & " . end($b);
strrpos finds the last occurrance of a specified string.
$str = '1, 2, 3';
$index = strrpos( $str, ',' );
if( $index !== FALSE )
$str[ $index ] = '&';
function fancy_implode($arr){
array_push($arr, implode(' and ', array_splice($arr, -2)));
return implode(', ', $arr);
}
I find this easier to read/understand and use
Does not modify the original array
Does not use regular expressions as those may fail if strings in the array contain commas, there could be a valid reason for that, something like this: array('Shirts (S, M, L)', 'Pants (72 x 37, 72 x 39)');
Delimiters don't have to be of the same length as with some of the other solutions
$bedroom_list = implode(", ", array_filter($bedroom_array));
$vars = $bedroom_list;
$last = strrchr($vars,",");
$last_ = str_replace(",","&",$last);
echo str_replace("$last","$last_",$vars);
<?php
$string = "3, 4, 5";
echo $string = preg_replace('/,( \d)$/', ' &\1', $string);
?>
Here's another way to do the replacement with a regular expression using a positive lookahead which doesn't require a backreference:
$bedroom_list = preg_replace('/,(?=[^,]*$)/',' &', implode(', ', $bedroom_array));
I am trying to un-format a number to it's original form but keep whether or not it is negative. Someone on stack overflow led me to this code that work's very nicely but it does not keep the negative.
Could anyone help me get a better fix on this?
EDIT - For USD Currency/normal numbers
Example:
1,234 = 1234
-1,234 = -1234
1,234.00 = 1234
1,234.56 = 1234.56
function numberUnformat($number)
{
$cleanString = preg_replace('/([^0-9\.,])/i', '', $number);
$onlyNumbersString = preg_replace('/([^0-9])/i', '', $number);
$separatorsCountToBeErased = strlen($cleanString) - strlen($onlyNumbersString) - 1;
$stringWithCommaOrDot = preg_replace('/([,\.])/', '', $cleanString, $separatorsCountToBeErased);
$removedThousendSeparator = preg_replace('/(\.|,)(?=[0-9]{3,}$)/', '', $stringWithCommaOrDot);
return (float) str_replace(',', '.', $removedThousendSeparator);
}
In case you have the ICU extension (which is bundled in PHP 5.3) available, try this:
$formatter = new NumberFormatter('en_US', NumberFormatter::DECIMAL);
echo $formatter->parse('-1,234.56');
Change your regular expression to match the negative numbers, too:
$cleanString = preg_replace('/([^\-0-9\.,])/i', '', $number);
Test cases:
echo numberUnformat('1,234')."\n";
echo numberUnformat('-1,234')."\n";
echo numberUnformat('1,234.00')."\n";
echo numberUnformat('1,234.56 ')."\n";
Output:
1234
-1234
1234
1234.56
Demo!
If you want to remove any extraneous minus signs in the middle of the string, too:
$cleanString = preg_replace('/[^0-9.,-]|(?<=.)-/', '', $number);
$onlyNumbersString = preg_replace('/[^0-9-]|(?<=.)-/', '', $number);
Note that you don't need the parentheses, backslash, or /i in your original.
I would actually add some parameters to the function to allow specification of grouping and decimal separators (and possibly allow ability to cast to float or decimal and go to a solution like this:
function number_unformat($num_string, $group_sep = ',', $dec_sep = '.', $cast_to_type = true) {
if (substr_count($num_string, $dec_sep) > 1) {
// input was invalid
throw new Exception('Inavlid string: `' . $num_string . '` passed to function. Too many decimal separators.');
}
// remove grouping separator
$string = str_replace($group_sep, '', $num_string);
if (true === $cast_to_type) {
// change any decimal separators to periods before casting
$string = str_replace($dec_sep, '.', $string, $count);
if ($count === 1) {
return (float)$string;
} else {
return (int)$string;
}
} else {
return $string;
}
}
Note that there is no need at all to use regular expression here.
A fairly quick (though imperfect) fix would be to change the first two lines of the function:
$cleanString = preg_replace('/([^-0-9\.,])/i', '', $number);
$onlyNumbersString = preg_replace('/([^-0-9])/i', '', $number);
Though this will cause a problem if you have a number like 2-434.43.
One could muck with the regular expressions to keep the negative, but to me it's simpler to do the following at the end:
$absvalue = (float) str_replace(',', '.', $removedThousendSeparator);
if ($number[0] == '-') {
$absvalue = $absvalue * -1.0;
}
return $absvalue;
I might have a syntax error in there, my PHP is rusty, but the idea is just to check and see if the input string starts with a negative sign, and if it does, multiply the result by negative 1.
I need a regular expression in PHP to remove from a string of telephone numbers the + or the 0 at the beginning of a number.
I have this function to remove every not-number characters
ereg_replace("[^0-9]", "", $sPhoneNumber)
but I need something better, all these examples should be...
$sPhoneNumber = "+3999999999999"
$sPhoneNumber = "003999999999999"
$sPhoneNumber = "3999999999999"
$sPhoneNumber = "39 99999999999"
$sPhoneNumber = "+ 39 999 99999999"
$sPhoneNumber = "0039 99999999999"
... like this
$sPhoneNumber = "3999999999999"
any suggestions, thank you very much!
As an alternative to regular expressions, you can use ltrim():
echo ltrim('003999999999999', '+0');
The second parameter is a character list string, in your case + and 0.
Note: This will not remove whitespace within the string, only the + and 0 from the beginning.
You can do this:
$result = preg_replace('~^[0\D]++|\D++~', '', $sPhoneNumber);
Just intval() afterwards to remove leading zeroes.
For removing the beginning + or 0, this should work
ereg_replace('^(\+|0)+?', '', $sPhoneNumber);
Just extend your expression by a few alternative cases:
ereg_replace("^\+|^00|[^0-9]", "", $sPhoneNumber)
See http://ideone.com/fzj16b
To be honest you don't need regex at all. Here is a clean solution as well.
// first remove spaces
// trim + and 0 characters at the beginning
ltrim(str_replace(' ', '', $sPhoneNumber), '+0');
this is my test code
<?php
$sPhoneNumber[0] = "+3999999999999";
$sPhoneNumber[1] = "003999999999999";
$sPhoneNumber[2] = "3999999999999";
$sPhoneNumber[3] = "39 99999999999";
$sPhoneNumber[4] = "+ 39 999 99999999";
$sPhoneNumber[5] = "0039 99999999999";
foreach ($sPhoneNumber as $number) {
$outcome = ltrim(str_replace(' ', '', $number), '+0');
echo $number . ':' . "\t" . $outcome . '(' . ($outcome === '3999999999999' ? 'true' : 'false') . ')' . "\n";
}
this is what I try to get:
My longest text to test When I search for e.g. My I should get My longest
I tried it with this function to get first the complete length of the input and then I search for the ' ' to cut it.
$length = strripos($text, $input) + strlen($input)+2;
$stringpos = strripos($text, ' ', $length);
$newstring = substr($text, 0, strpos($text, ' ', $length));
But this only works first time and then it cuts after the current input, means
My lon is My longest and not My longest text.
How I must change this to get the right result, always getting the next word. Maybe I need a break, but I cannot find the right solution.
UPDATE
Here is my workaround till I find a better solution. As I said working with array functions does not work, since part words should work. So I extended my previous idea a bit. Basic idea is to differ between first time and the next. I improved the code a bit.
function get_title($input, $text) {
$length = strripos($text, $input) + strlen($input);
$stringpos = stripos($text, ' ', $length);
// Find next ' '
$stringpos2 = stripos($text, ' ', $stringpos+1);
if (!$stringpos) {
$newstring = $text;
} else if ($stringpos2) {
$newstring = substr($text, 0, $stringpos2);
} }
Not pretty, but hey it seems to work ^^. Anyway maybe someone of you have a better solution.
You can try using explode
$string = explode(" ", "My longest text to test");
$key = array_search("My", $string);
echo $string[$key] , " " , $string[$key + 1] ;
You can take i to the next level using case insensitive with preg_match_all
$string = "My longest text to test in my school that is very close to mY village" ;
var_dump(__search("My",$string));
Output
array
0 => string 'My longest' (length=10)
1 => string 'my school' (length=9)
2 => string 'mY village' (length=10)
Function used
function __search($search,$string)
{
$result = array();
preg_match_all('/' . preg_quote($search) . '\s+\w+/i', $string, $result);
return $result[0];
}
There are simpler ways to do that. String functions are useful if you don't want to look for something specific, but cut out a pre-defined length of something. Else use a regular expression:
preg_match('/My\s+\w+/', $string, $result);
print $result[0];
Here the My looks for the literal first word. And \s+ for some spaces. While \w+ matches word characters.
This adds some new syntax to learn. But less brittle than workarounds and lengthier string function code to accomplish the same.
An easy method would be to split it on whitespace and grab the current array index plus the next one:
// Word to search for:
$findme = "text";
// Using preg_split() to split on any amount of whitespace
// lowercasing the words, to make the search case-insensitive
$words = preg_split('/\s+/', "My longest text to test");
// Find the word in the array with array_search()
// calling strtolower() with array_map() to search case-insensitively
$idx = array_search(strtolower($findme), array_map('strtolower', $words));
if ($idx !== FALSE) {
// If found, print the word and the following word from the array
// as long as the following one exists.
echo $words[$idx];
if (isset($words[$idx + 1])) {
echo " " . $words[$idx + 1];
}
}
// Prints:
// "text to"
I have searched everywhere but can't find a solution that works for me.
I have the following:
$bedroom_array = array($studio, $one_bed, $two_bed, $three_bed, $four_bed);
For this example lets say:
$studio = '1';
$one_bed = '3';
$two_bed = '3';
I then use the implode function to put a comma in between all the values:
$bedroom_list = implode(", ", array_filter($bedroom_array));
echo $bedroom_list;
This then outputs:
1, 2, 3
What I want to do is find the last comma in the string and replace it with an &, so it would read:
1, 2 & 3
The string will not always be this long, it can be shorter or longer, e.g. 1, 2, 3, 4 and so on. I have looked into using substr but am not sure if this will work for what I need?
Pop off the last element, implode the rest together then stick the last one back on.
$bedroom_array = array('studio', 'one_bed', 'two_bed', 'three_bed', 'four_bed');
$last = array_pop($bedroom_array);
$string = count($bedroom_array) ? implode(", ", $bedroom_array) . " & " . $last : $last;
Convert & to the entity & if necessary.
if you have comma separated list of words you may use:
$keyword = "hello, sadasd, sdfgdsfg,sadfsdafsfd, ssdf, sdgdfg";
$keyword = preg_replace('/,([^,]*)$/', ' & \1', $keyword);
echo $keyword;
it will output:
hello, sadasd, sdfgdsfg,sadfsdafsfd, ssdf & sdgdfg
A one-liner alternative, that will work for any size array ($b = $bedroom_array):
echo count($b) <= 1 ? reset($b) : join(', ', array_slice($b, 0, -1)) . " & " . end($b);
strrpos finds the last occurrance of a specified string.
$str = '1, 2, 3';
$index = strrpos( $str, ',' );
if( $index !== FALSE )
$str[ $index ] = '&';
function fancy_implode($arr){
array_push($arr, implode(' and ', array_splice($arr, -2)));
return implode(', ', $arr);
}
I find this easier to read/understand and use
Does not modify the original array
Does not use regular expressions as those may fail if strings in the array contain commas, there could be a valid reason for that, something like this: array('Shirts (S, M, L)', 'Pants (72 x 37, 72 x 39)');
Delimiters don't have to be of the same length as with some of the other solutions
$bedroom_list = implode(", ", array_filter($bedroom_array));
$vars = $bedroom_list;
$last = strrchr($vars,",");
$last_ = str_replace(",","&",$last);
echo str_replace("$last","$last_",$vars);
<?php
$string = "3, 4, 5";
echo $string = preg_replace('/,( \d)$/', ' &\1', $string);
?>
Here's another way to do the replacement with a regular expression using a positive lookahead which doesn't require a backreference:
$bedroom_list = preg_replace('/,(?=[^,]*$)/',' &', implode(', ', $bedroom_array));