I have a string '1/2' and i need to get a float value 0.5 from it.
Other examples:
Operation: $operation = '5/8';
Wanted value: $value = 0.625;
You can use eval, also please note your are not looking for an int as they are whole numbers.
<?php
$operation = '1/2';
eval('$value = ' . $operation . ';');
echo $value;
?>
This will work if you only have one "/".
$str = '2/5';
$newStr = explode('/', $str);
echo $newStr[0]/$newStr[1];
Edited.
Not elegant because eval is used, but working.
$operation = '1/2';
function stringCalc($operation){
return eval('return '.$operation.';');
}
$value = stringCalc($operation);
Related
I'm in a situation where the CSV file is getting rid of the leading zero before my import and I need to be able to account for that. Let's say that I have my value as the following:
-.0982739 -> I would want all case scenarios where it's -. to turn into -0. - Here are my attempts:
if (str_contains($this->longitude, '-.')) {
$this->longitude = '0' . $this->longitude;
};
Outputs: 00-.0989070
if ($this->longitude[0] == '.') {
$this->longitude = '0' . $this->longitude;
}
Outputs: -.0989070
To simplify things, basically any . that has nothing before it, add in a 0, otherwise use the value given.
I will need it for both longitude and latitude.
/^([-+])?\./
The above regex matches the signs - and + if they are present and immediately followed by a .. Now, capture the matched group 1 in the regex which is ([-+])? and append 0. followed by all digits after . by taking substr of the current string.
<?php
$a = ".0982739";
if(preg_match('/^([-+])?\./',$a, $matches) === 1){
$prefix = $matches[1] ?? '';
$a = $prefix . '0.' . substr($a,$prefix == '' ? 1 : 2);
}
echo $a;
Try this :
<?php
$x = -.54321 ;
echo $x . "\r\n" ;
$x = "-.12345" ;
echo $x . "\r\n" ;
echo floatval($x) . "\r\n" ;
echo sprintf("%0.5f", $x) ;
?>
I assume your CSV is returning only string values, because as soon as I echo a "native" float, the echo is just fine.
As soon as your float is correctly formatted, you can catch it in a string value if needed.
You could use str_replace:
$this->longitude = ltrim($this->longitude, '+');// remove leading +
if ($this->longitude[0]=='.' || substr($this->longitude, 0, 2)=='-.')) {
$this->longitude = str_replace('.', '0.', $this->longitude);
}
The if condition matches any string that begins with '.' or '-.' And if so, str_replace replaces the . with 0.
`$var = 0.0989070;
$neg = -$var; // easiest
$neg = -1 * $var; // bit more explicit
$neg = 0 - $var; // another version`
You could check for numbers before dot....
<?php
if (str_contains($this->longitude, '.')) {
$beforedot = strstr($this->longitude,'.',true); //Get anything before
if (is_numeric($beforedot)) { echo "do nothing"; } //check if is number do nothing
else {
$this->longitude = str_replace('.', '0.', $this->longitude); //else do replace . with 0.
}
};
?>
I created a class and assigned -.0982739 to a property called $longitude. In the constructor I did echo $this->longitude and it came out as -0.0982739 which I believe is exactly as you want it to be. I couldn't manage to reproduce it.
<?php
class Test
{
private $longitude = -.0982739;
public function __construct()
{
}
public function test()
{
echo $this->longitude;
}
}
<?php
include "Test.php";
$test = new Test();
$test->test();
I've been working with this code
<?php
class PerchTemplateFilter_sol_en_cat_path extends PerchTemplateFilter {
public function filterAfterProcessing($value, $valueIsMarkup = false) {
// ORIGINAL STRING: solutions-en/rail-technologies/track-components/name-of-product
$mystring = $value;
$replace = ['solutions-en', '%2F'];
$str = '';
$oldstr = str_replace($replace, $str, $mystring);
$str_to_insert = 'XXX';
$findme = '/';
$pos = strpos($mystring, $findme); // I NEED THIS TO INSERT $str_to_insert AFTER THE SECOND FORWARD SLASH FOUND IN THE ORIGINAL STRING?
$value = substr_replace($oldstr, $str_to_insert, $pos, 0);
return $value;
// $value: /rail-technologies/track-components/XXX/name-of-product
// Insert string at specified position
// https://stackoverflow.com/questions/8251426/insert-string-at-specified-position
}
}
PerchSystem::register_template_filter('sol_en_cat_path', 'PerchTemplateFilter_sol_en_cat_path');
?>
My string is: solutions-en/rail-technologies/track-components/name-of-product
I want to end up with: /rail-technologies/XXX/track-components/name-of-product
XXX is only a placeholder value
I guess I need to do something with $pos to set where I want XXX to be added to the string.
I need to insert after the second forward slash, as the string may contain different text
The code above outputs this string: /rail-technoXXXlogies/track-components/ewosr-switch-lock
I can't seem to figure out how to insert XXX after the second forward slash.
Hope someone can provide some help.
How about explode to array, then implode the first two items.
Join with xxx and implode the rest?
function AddInTheMiddle($start, $where, $what){
$arr = explode("/", $what);
$str = implode("/", array_splice($arr,$start,$where)) . '/xxx/' . implode("/", $arr);;
return $str;
}
$str = 'solutions-en/rail-technologies/track-components/name-of-product';
$str = AddInTheMiddle(1, 2, $str);
https://3v4l.org/m98io
Thank you Andreas, your post gave me the nudge I needed. I did this in the end.
// ORIGINAL $value: solutions-en/rail-technologies/track-components/name-of-product
$str = explode("/", $value);
$value = $str[1] . '/' . 'solutions' . '/' . $str[2] . '/';
return $value;
// Removed: solutions-en
// Added: solutions
// $value: rail-technologies/solutions/track-components/name-of-product
I was able to add the name-of-product to the end of the new string elsewhere in my template.
What is the most efficient pattern to replace dots in dot-separated string to an array-like string e.g x.y.z -> x[y][z]
Here is my current code, but I guess there should be a shorter method using regexp.
function convert($input)
{
if (strpos($input, '.') === false) {
return $input;
}
$input = str_replace_first('.', '[', $input);
$input = str_replace('.', '][', $input);
return $input . ']';
}
In your particular case "an array-like string" can be easily obtained using preg_replace function:
$input = "x.d.dsaf.d2.d";
print_r(preg_replace("/\.([^.]+)/", "[$1]", $input)); // "x[d][dsaf][d2][d]"
From what I can understand from your question; "x.y.z" is a String and so should "x[y][z]" be, right?
If that is the case, you may want to give the following code snippet a try:
<?php
$dotSeparatedString = "x.y.z";
$arrayLikeString = "";
//HERE IS THE REGEX YOU ASKED FOR...
$arrayLikeString = str_replace(".", "", preg_replace("#(\.[a-z0-9]*[^.])#", "[$1]", $dotSeparatedString));
var_dump($arrayLikeString); //DUMPS: 'x[y][z]'
Hope it helps you, though....
Using a fairly simple preg_replace_callback() that simply returns a different replacement for the first occurrence of . compared to the other occurrences.
$in = "x.y.z";
function cb($matches) {
static $first = true;
if (!$first)
return '][';
$first = false;
return '[';
}
$out = preg_replace_callback('/(\.)/', 'cb', $in) . ((strpos('.', $in) !== false) ? ']' : ']');
var_dump($out);
The ternary append is to handle the case of no . to replace
already answered but you could simply explode on the period delimiter then reconstruct a string.
$in = 'x.y.z';
$array = explode('.', $in);
$out = '';
foreach ($array as $key => $part){
$out .= ($key) ? '[' . $part . ']' : $part;
}
echo $out;
i have one string
$str ='california 94063';
now i want california and 94063 both in diferent variable.
string can be anything
Thanks in advance....
How about
$strings = explode(' ', $str);
Assuming that your string has ' ' as a separator.
Then, if you want to find the numeric entries of the $strings array, you can use is_numeric function.
Do like this
list($str1,$str2)=explode(' ',$str);
echo $str2;
If your string layout is always the same (say: follows a given format) then I'd use sscanf (http://www.php.net/manual/en/function.sscanf.php).
list($str, $number) = sscanf('california 94063, "%str %d");
<?php
$str ='california 94063';
$x = preg_match('(([a-zA-Z]*) ([0-9]*))',$str, $r);
echo 'String Part='. $r[1];
echo "<br />";
echo 'Number Part='.$r[2];
?>
If text pattern can be changed then I found this solution
Source ::
How to separate letters and digits from a string in php
<?php
$string="94063 california";
$chars = '';
$nums = '';
for ($index=0;$index<strlen($string);$index++) {
if(isNumber($string[$index]))
$nums .= $string[$index];
else
$chars .= $string[$index];
}
echo "Chars: -".trim($chars)."-<br>Nums: -".trim($nums)."-";
function isNumber($c) {
return preg_match('/[0-9]/', $c);
}
?>
In PHP, how can you replace the second and third character of a string with an X so string would become sXXing?
The string's length would be fixed at six characters.
Thanks
It depends on what you are doing.
In most cases, you will use :
$string = "string";
$string[1] = "X";
$string[2] = "X";
This will sets $string to "sXXing", as well as
substr_replace('string', 'XX', 1, 2);
But if you want a prefect way to do such a cut, you should be aware of encodings.
If your $string is 我很喜欢重庆, your output will be "�XX很喜欢" instead of "我XX欢重庆".
A "perfect" way to avoid encoding problems is to use the PHP MultiByte String extension.
And a custom mb_substr_replace because it has not been already implemented :
function mb_substr_replace($output, $replace, $posOpen, $posClose) {
return mb_substr($output, 0, $posOpen) . $replace . mb_substr($output, $posClose + 1);
}
Then, code :
echo mb_substr_replace('我很喜欢重庆', 'XX', 1, 2);
will show you 我XX欢重庆.
Simple:
<?php
$str = "string";
$str[1] = $str[2] = "X";
echo $str;
?>
For replacing, use function
$str = 'bar';
$str[1] = 'A';
echo $str; // prints bAr
or you could use the library function substr_replace as:
$str = substr_replace($str,$char,$pos,1);
similarly for 3rd position
function mb_substr_replace($string, $replacement, $start, $length=0)
{
return mb_substr($string, 0, $start) . $replacement . mb_substr($string, $start+$length);
}
same as above, but standardized to be more like substr_replace (-substr- functions usually take length, not end position)