PHP parse field and calculate difference [closed] - php

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
Can someone provide a way to parse a field with a format like the following and take the difference between the two values between the colons.
bot1:11874-12227:top
For example, the resultant field would be equal to 12227-11874 = 353.
I think something like a scan by delimiter and then eval the negative of the difference.

$string = "bot1:11874-12227:top";
$parts = explode(":", $string);
$numbers = explode("-", $parts[1]);
$difference = (($numbers[1] - $numbers[0]) > 0) ? $numbers[1] - $numbers[0] : $numbers[0] - $numbers[1];
echo $difference;

Easy just use a regex with preg_match:
$string = 'bot1:11874-12227:top';
preg_match("#[A-Za-z]+[0-9]?:([0-9]+)([-|+|*|//])([0-9]+):[A-Za-z]+#", $string, $matches);
echo '<pre>';
print_r($matches);
echo '</pre>';
The results would be:
Array
(
[0] => bot1:11874-12227:top
[1] => 11874
[2] => -
[3] => 12227
)
Then just do the following for the math:
echo abs($matches[1] - $matches[3]);
Now, note how $matches[2] matches the mathematical operator? Well, why not make use of that to do the following with create_function:
$string_to_math_results = create_function("", "return ($matches[1] $matches[2] $matches[3]);" );
echo abs($string_to_math_results());
So bring it all together like this. Now you can not only parse the values out of the string, but perform basic calculations based on the value in the strings:
$string = 'bot1:11874-12227:top';
preg_match("#[A-Za-z]+[0-9]?:([0-9]+)([-|+|*|//])([0-9]+):[A-Za-z]+#", $string, $matches);
$string_to_math_results = create_function("", "return ($matches[1] - $matches[3]);" );
echo abs($string_to_math_results());

Related

PHP explode string [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I have this string: 0|DY1497ORYOSLDY932OSLCPH|1|0|0
and I need to explode it like that:
0| DY1497 ORY OSL DY932 OSL CPH |1|0|0
$string1 = 'DY1497';
$string2 = 'ORY';
$string3 = 'OSL';
$string4 = 'DY932';
$string5 = 'OSL';
$string6 = 'CPH';
I searched, but all I could find is how to explode when the text is separated with /, -, etc. Any ideas?
The best choice is probably a regex:
if (preg_match('/|(.{6})(.{3})(.{3})(.{5})(.{3})(.{3})|/', $string, $matches)) {
echo $matches[1];
echo $matches[2];
echo $matches[3];
echo $matches[4];
echo $matches[5];
echo $matches[6];
}
This divides the string simply by length in characters. You may need to modify this as needed. See http://regular-expressions.info
I suggest to use substr() if you know the exact position of the characters you need
Son, it looks to me like you searching for some specific tokens up in this here string. What I reckon you can do is, make yerself one array outa little search patterns you might be a looking fer. Something like this here:
$patterns = array('ORY', 'OSL', 'CPH', 'DY[\d]+');
Then you can make yerself a nice big regexp outa that:
$regexp = '/(' . implode('|', $patterns) . ')/';
Then, what you gonna do is, use preg_match_all to find every one of them fellers thisaway:
preg_match_all($regexp, $string, $matches);
Now, you do that and then looka what you got in $matches. I'd wager it has what you need.
Another way of splitting up strings that consists of fixed length fields is with 'unpack' which is very suited to this job.
here is some tested code that demonstrates it:
<?php
$origSource = '0|DY1497ORYOSLDY932OSLCPH|1|0|0';
// expected result
$string1 = 'DY1497';
$string2 = 'ORY';
$string3 = 'OSL';
$string4 = 'DY932';
$string5 = 'OSL';
$string6 = 'CPH';
// get the string we are interested in...
$tempStr = explode('|', $origSource);
$source = $tempStr[1]; // string with fixed length fields
/* debug */ var_dump($source);
// define where the fixed length fields are and the indexes to call them in the output array
$format = 'A6field1/' . 'A3field2/' . 'A3field3/'. 'A5field4/'. 'A3field5/'. 'A*field6/' ; // make it clear where the fields are...
$dest = unpack($format, $source);
/* debug */ var_dump($dest);
?>
firstly you have to concat your string with a special character like -,#,$ etc...
then you can explode it.
after that you may use the following syntax in php to explod string......
<?php
$string= "0|$DY1497$ORY$OSL$DY932$OSL$CPH$|1|0|0";
$pieces = explode("$", $string);
?>
For see your Result:---
<?php
foreach ($pieces as $value)
{
echo "piece: $value<br />";
}
?>
I hope it will help you.

Reverse a number inside a string in PHP [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a UTF8 string that contains letters and digits. For example:
"Hello World 37. What? 24 last 6650"
and I want to reverse only the digits but keep the numbers in the same place.
The output should be:
"Hello World 73. What? 42 last 0566"
echo preg_replace_callback('/\d+/', function (array $m) { return strrev($m[0]); }, $string);
Before I posted the question, I thought about it and got an idea that works for me, so I'm only posting this question to enrich the database.
function reverseNumbersInString($str){
$tokens = explode(" ", $str);
$res = "";
for ($i = 0; $i < sizeof($tokens); $i++){
if (intval($tokens[$i] > 0 )){
$tokens[$i] = strrev($tokens[$i]);
}
$res .= " " . $tokens[$i];
}
return $res;
}
Maybe something like this:
$string = "Hello World 37. What? 24 last 6650";
preg_match_all('/\d+/', $string, $matches, PREG_OFFSET_CAPTURE);
foreach ($matches[0] as $numberData) {
$numberArray = str_split($numberData[0]);
$reversedNumber = implode('', array_reverse($numberArray));
$string = substr_replace($string, $reversedNumber, $numberData[1], strlen($numberData[0]));
}
This should do it:
$stringWithReversedNumbers = preg_replace_callback(
'/\d+/',
function ($matches) {
return strrev($matches[0]);
},
$originalString
);
Alternatively, if you ONLY want to operate on numbers that are distinct words (i.e. not part of another word, as in if you want hello123goodbye to remain unmodified because the 123 isn't a word by itself), change \d+ to \b\d+\b

Convert comma separated string into list [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a string eg:
$string = "word1,word2,word3,word4";
I need to echo this into <li> elements using PHP. So $string becomes:
<li>word1</li>
<li>word2</li>
<li>word3</li>
<li>word4</li>
Like this:
$string = "word1,word2,word3,word4";
$string = explode(",",$string);
foreach ($string as $str) {
echo "<li>".$str."</li>";
}
You can explode() the string into an array, loop through it, and output the results into a list option.
Try this:
echo "<li>" . str_replace ("," , "</li><li>" , $string) . "</li>";
For what you are trying to accomplish, the explode approach adds unnecessary overhead.
You may try this
$string = "word1,word2,word3,word4";
echo "<ul>";
foreach(explode(',', $string) as $li) {
echo "<li>$li</li>";
}
echo "</ul>";
DEMO.

Output Value conversion in PHP [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am getting Output value like 0.000098, 0.000854.
But I need 98, 854 instead.
How to do this?
<?php
$str = '0.00009801';
$r = array();
$ret = preg_match('/[1-9]+[0-9]+/', $str, $r);
echo $r[0];
You can use
$num = '0.000098000';
$newNum = preg_replace('/^[0\.]+/', '', $num);
The $newNum will contain the required output (98000 in the case above) after replacing all the 0 and . from the starting.
So you want to take a string, split it by a comma and remove spaces , multiply by 1000000 then put it back together. Try doing this:
$str = "0.000098, 0.000854";
echo implode(",",array_map(function($a){ return 1000000 * trim($a); },explode(",", $str)));
or in a slightly more readable form:
$parts = explode(",", $str);
$parts = array_map(function($a) { return 1000000 * trim($a); }, $parts);
echo implode(",", $parts);
function convertVal($value) {
for($i=0;$i<strlen($value);$i++){
$a = strpos($value,substr($value,$i,$i+1));
if($a>0){
$pos = substr($value,$a-1,strlen($value));
}
}
return $pos;
}
echo convertVal("0000980");

Reverse Order of String like "Hello Word" reverse as "Word Hello" in PHP [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
i need to reverse String "Hello Word" into "Word Hello", it could be "My Name is Khan" reverse into "Khan is Name My" in PHP
$str = "My Name is Khan";
$reverse = implode(" ",array_reverse(explode(" ", $str)));
echo $reverse;
Result is Khan is Name My.
explode splits the string into an array in accordance to the delimiter, which in this case is " ". array_reverse is self-explanatory, it reverses the order of the array. implode then joins the string using the delimiter.
You might think to code something to show then let us help you with the answer, but let me describe the logic, since you are going to input it as a string, you might think to split the character based on the character you wanted to split
you might consider this EXPLODE
After you finish and put that split into an array. You can reverse it back using looping or perhaps you want to reverse using THIS
$string = "My Name is Khan";
$new = explode(' ', $string);
$new = array_reverse($new);
print_r(implode(' ', $new));
At first, requirement is: reverse the order of words not alphabets.
So, need to split the string by spaces(as words are separated by spaces).
This way, an array is generated like:
array('World', 'Hello');
Change the sequence of array using array_reverse()
The resulting array would be:
array('Hello', 'World');
Now, again join the above array by space:
The resulting string would be:
Hello World
Try this:
<?php
$name = 'World Hello';
$temp = explode(' ', $name);
echo '<pre>';
print_r($temp);
echo '</pre>';
$arr = array_reverse($temp);
echo '<pre>';
print_r($arr);
echo '</pre>';
$str = implode(' ', $arr);
echo $str;
?>

Categories