i have an aribitrary piece of text, that is supplied through magento within the CMS,
the text that is retrieved may have a price within it. So for example
Delivery text
Orders over €200 are delivered Free Of Charge. €10 charge for orders
under €200. There may be additional charges for heavy goods.
How would i go about replacing each occurance of a price, so in the case above i would change
€200
€10
€200
I want to replace these prices based on the current currency being used.
$fromCur = 'EUR'; // currency code to convert from
$toCur = 'USD'; // currency code to convert to
$toCurrencyPrice = Mage::helper('directory')->currencyConvert($fromCurrencyPrice, $fromCur, $toCur);
This is how i will convert the prices, the only thing is , i do not know how i will find the prices within the text
Here is what i have tried so far
//the text to search
$text = 'Orders over €200 are delivered Free Of Charge. €10 charge for orders under €200. There may be additional charges for heavy goods.';
$matches = array();
//find a price with a euro symbol
preg_match_all("/€[0-9]+/", $text, $matches);
$ints = array();
$counter = 0;
//remove the euro symbol
foreach ($matches[0] as $match) {
//echo substr( $match,6) . '<br/>';
$ints[$counter] = substr( $match,6);
$counter++;
}
//now i know i have to convert it to my price, but my issue is, how do i now replace new values, with the old values inside the $ text varaible
Lets say i wants to change the matches found , with the elements in $ints (the price without the euro symbol). How would i do this?
Not entire solution, but to begin, you can extract prices and unit using :
$text = "I bought a shoes 33 $, a tee shirt 44 $ and a short 55 €.";
$match = array();
preg_match_all("/([0-9]+)[ ]*(€)|([0-9]+)[ ]*([$])/", $text, $match);
print_r($match);
It will give you:
Array
(
[0] => Array
(
[0] => 33 $
[1] => 44 $
[2] => 55 €
)
[1] => Array
(
[0] =>
[1] =>
[2] => 55
)
[2] => Array
(
[0] =>
[1] =>
[2] => €
)
[3] => Array
(
[0] => 33
[1] => 44
[2] =>
)
[4] => Array
(
[0] => $
[1] => $
[2] =>
)
)
And you will able to decide what logic you want to apply (knowing values, and money sign)
The PHP documentation is a good place to start. You have to use string search functions. Try figuring out yourself, you have the whole PHP documentation to look in. Just search string search php on google and you will find loads of informations.
Here are some functions that might help you :
http://php.net/manual/en/function.strpos.php
http://php.net/manual/en/function.preg-match.php
I think pregmatch will suit your needs. Understand that function and use it in your scope.
Good luck !
Assuming you always have € as your incoming currency, try next code:
$string = 'Orders over €200 are delivered Free Of Charge. €10 charge for orders under €200. There may be additional charges for heavy goods.';
$pattern = "#€[0-9]{1,}#";
$newStr = preg_replace_callback($pattern, create_function(
'$matches',
'return Mage::helper(\'directory\')->currencyConvert($matches[0], \'EUR\', \'USD\');'
), $string);
echo $newStr;
I haven't tested it, but it should work;
UPDATE:
I just thought about convert you have, and you probably need to remove and then add the currency symbol first; but you should have a starting point for that - just play with return function
Related
So I'm using the next thing:
<?php
$string='JUD. NEAMT, SAT ROMEDC ALEXANDRE COM. COMENKA, STR. EXAMMS RANTEM, NR.6';
$result=preg_split("/(?:JUD.\s*|\s*SAT\s*|\s*COM\.\s*|\s*STR.\s*|\s*SECTOR\s*|\s*B-DUL\s*|\s*NR\.\s*|\s*ET.\s*|\s*MUN\.\s*|\s*BL.\s*|\s*SC\.\s*|\s*AP\.\s*)/", $string);
array_walk($result,function($value,$key) use (&$result){
if(stristr($value, ","))
{
$result[$key]=explode(",", $value)[0];
}
});
print_r(array_filter($result));
the output would be:
Array
(
[1] => NEAMT
[2] => ROMEDC ALEXANDRE
[3] => COMENKA
[4] => EXAMMS RANTEM
[5] => 6
)
The main problem is that $string is different each time and can contain different parameters like 'SAT' could simply not appear in another string because is replaced by 'SECTOR'.
All these are localization words like House number('NR.') or Town name('JUD').
What I want is to convert the above array into something like this:
Array
(
['JUD'] => NEAMT
['SAT'] => ROMEDC ALEXANDRE
['COM'] => COMENKA
['STR'] => EXAMMS RANTEM
['NR'] => 6
)
I hope you got the idea:
I'm getting from a string 'address' different parameters like apartment number , building number and so on (it depends each time on the customer-- he might be living at a house so there is no apartment number) so having words instead of numbers in the array would help me output the info in different columns.
Any idea is welcome.
Thank you.
$string='JUD. NEAMT, SAT ROMEDC ALEXANDRE COM. COMENKA, STR. EXAMMS RANTEM, NR.6';
//fix missing commas
$string = preg_replace('#([A-Z]+) ([A-Z]+\.)#',"$1, $2",$string);
//a trick to fix non space on `NR.6`
$string = str_replace(['.',' '],['. ',' '],$string);
//get the part seperated by comma, trim to remove spaces
$ex = array_map('trim',explode(',',$string));
//iterate over it
foreach($ex as $e){
//explode the part by space
$new = array_map('trim',explode(' ',$e));
//take the first part as key, remove spaces and dot
$key = trim(array_shift($new),' . ');
//collect via key and implode rest with a space
$coll[$key]=implode(' ',$new);
}
//done
print_r($coll);
Result:
Array
(
[JUD] => NEAMT
[SAT] => ROMEDC ALEXANDRE
[COM] => COMENKA
[STR] => EXAMMS RANTEM
[NR] => 6
)
a fast lane to rome...
I am writing a php script to dissect information copied from an external webpage.
I paste the external data into a text area, which is passed through PHP's post function.
One of the lines looks something like this:
972 Date Name Information
The issue is, the first space after "972" is not actually a space. When I execute the strpos function with needle " ", it returns the position of the space following "Date". Possible solutions are:
Execute strpos which searches for all possible whitespaces.
Find some way to make my browser echo out the actual whitespace code so I know what to enter for the needle.
Suggestions?
You can use Regular Expression to intercept any character that is a whitespace of any kind, plus chr(160) to intercept non-breaking space. This should work:
$str = "972 Date Name Information";
if (preg_match_all('/[\s'.chr(160).']/', $str, $matches, PREG_OFFSET_CAPTURE)) {
print_r($matches);
}
It should give you the following result:
Array
(
[0] => Array
(
[0] => Array
(
[0] => �
[1] => 3
)
[1] => Array
(
[0] =>
[1] => 8
)
[2] => Array
(
[0] =>
[1] => 13
)
)
)
where the numbers at index [1] are the positions of the various whitespace characters in the string.
I have tried for the last two days now searching on google and in all the forums, but can't seem to find any answer that remotely helps me with this problem .
I have a stock feed .csv file which I need to change the values of the shoe sizes to work with Woocommerce. The shoe sizes are different on each row.
The sizes in the csv are listed like this: 4-10, 5-12, 3-9 etc. one set of numbers per row 4-10. I have inputed the file into an array in my php script.
So for each shoe I have an array like this:
Array
(
[0] => 4578
[1] => kors
[2] => red
[3] => wedge
[4] => 4-10
)
I need to take the last value e.g. 4-10 and change them to something like this: 4|5|6|7|8|9|10.
So basically I need to take the first number in the element and increment it by 1 and separate it with the pipe character " | "until it reaches the value of the last number. Then I need it to replace the 4-10 in the element with the 4|5|6|7|8|9|10.
This should work for you:
(Here I first get the last element of the array and explode() it with - as delimiter. After this I simply create an array with range() where I use the $start and $end variable. At the end I simply save the element back by implode()'ing it.)
<?php
$arr = [4578, "kors", "red", "wedge", "4-10"];
list($start, $end) = explode("-", $arr[count($arr)-1]);
$arr[count($arr)-1] = implode("|", range($start, $end));
print_r($arr);
?>
output:
Array ( [0] => 4578 [1] => kors [2] => red [3] => wedge [4] => 4|5|6|7|8|9|10 )
$this->row['contents'] = strip_tags($this->row['contents']);
$this->words = explode(" ", $this->row['contents']);
The code above should create an array with a key => value pair for each word of $this->row['contents']. Under normal circumstances it works just fine, but with a string such as:
This costs U$ 10.40 per liter.
It will separate as
[0] => This
[1] => Costs U$
[2] => 10.40 per
[3] => liter.
Any ideas how to solve this?
maybe this code help you
$this->words = preg_split('/\s+/', $this->row['contents']);
The file below, can be setup using any JPG file from PhotoShop that has XMP data. In the 'pattern', replace 'eat:' with 'dc:' or any namespace returned from the '$string'.
Calling $string (1) using following array setup it produces a print_r array that looks like: (2)
If you uncomment the line ubove (1a), it will print to the browse, copy & paste into the line below (1a). this should produce an array that looks like: (3)
Why the difference print_r readings, when it's the same string?
How do I get it to behave like (3); ... better yet how do I make it end up like the(4)?
<?php
header("Content-Type: text/html; charset=utf-8");
$filename = "2012-04-24_WestCoast_2.jpg";
echo '<img src="'. $filename . '" alt="'. $filename . '" title="' . $filename . '" width="350" /><p />';
$source = file_get_contents($filename);
$xmpdata_start = strpos($source,'<x:xmpmeta');
$xmpdata_end = strpos($source,"</rdf:Description>");
$xmplenght = $xmpdata_end-$xmpdata_start;
$xmpdata = substr($source,$xmpdata_start,$xmplenght+18);
$string = htmlentities($xmpdata); //(1)
//if (is_string($string)) {
// echo "is a string\n"; //TRUE
//} else {
// echo "is not a string\n";
//}
//$string = print_r("'".$string."';");
// (1a)=====================================
//$string = '<x:xmpmeta xmlns: === Truncated for simplicity ===x="adobe:ns:meta/" x:xmptk="Adobe XMP Core 5.3-c011 66.145661, 2012/02/06-14:56:27 "> <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"></rdf:Description>';
$pattern = '/eat:(.*?)="(.*?)"/is';
preg_match_all($pattern, $string, $matches);
$group = array($matches[1], $matches[2]);
// foreach($group as &$match);
echo '<pre>';
// print_r ($match);
print_r ($group);
echo '</pre>';
?>
(2)=====================================
// If i just call the '$string', this is what i get:
Array
(
[0] => Array
(
)
[1] => Array
(
)
)
(3)=====================================
// If I uncomment (1), the '$string' that I pasted inside the file, i get this:
Array
(
[0] => Array
(
[0] => Biography
[1] => Title
[2] => object_description
[3] => Medium
[4] => in_height
[5] => in_width
[6] => in_depth
[7] => Dated
[8] => Photograph
)
[1] => Array
(
[0] => American B1942 Castine, Maine
[1] => Reunion Dinner Party at the Slanted Door
[2] => Nancy Freeman, Tim Patterson The Slanted Door San Francisco Calf.
[3] => photography
[4] => 2736
[5] => 3648
[6] => # 240 dpi
[7] => April 24, 2012
[8] => PrimaryImage
)
)
(4)=====================================
// This is what i'm trying to get too:
Biography: American B1942 Castine, Maine
Title: Reunion Dinner Party at the Slanted Door
object_description: Reunion Dinner Party at the Slanted Door
Nancy Freeman, Tim Patterson The Slanted Door San Francisco Calf.
Medium: photography
in_height: 2736
in_width: 3648
in_depth: # 240 dpi
Dated: April 24, 2012
Photograph: PrimaryImage
I'm not clear on what the issue is with the string being set inside or outside of file. It is unclear what you are trying to explain.
The output of the array(3) is caused by the brackets in the Regular Expression. I don't know the exact reason for this, but to get the results you want(4) you could use a loop to join the two arrays in a new array.
Note: What your doing with $group is making an array of arrays. You are not merging the two arrays into one. To merge the arrays you need to iterate through both arrays and merging each element as new element of new array.
example:
for($i=0; $i<match[0].length; $i++){
$result[i] = $match[0][i]. ": " .$match[1][i];
}
Im rusty on my php, but that is the idea for merging the arrays.
--EDIT--
Now that I understand what you are trying to do I see two possible places where problems may occur. First is: are you 100% sure the image you are using contains any meta data in the fields you want? Im not sure of the exact nature of meta data, but I do know there will be the required data set by the computer(what you filtered out with the start and end points), and the custom data. If blank it might not even be included.
Second possible issue is how you are chunking up the meta data. Maybe try writing to Regular Expressions to strip the start and end from the string. Replace everything in front of a set of characters with "" and do a similar expression for the back.
Also the variable you set for $group is the exact same thing that $match was. You took the two arrays that where contained in the array %match and assigned them to an array called $group. Just a FYI. Use the sudo code I posted earlier to design the loop that will actually combine the two arrays into one.
Good Luck. Maybe when I get php set up on testing computer I will play with the code to see what exactly is happening.
Well it looks like i get to answer my own question of "Why it is a called 'string' invisible to an array?".
The answer is: When it's preceded by a call to 'htmlentities()'.
Now I'm not really sure why it happens but it does happen and the instant I went back and checked all my assumptions ... that 'htmlentities()' would clean up the raw string. Commenting out 'htmlentities()' made everything work.
Is this a bug? I personally don't know, and i don't have the necessary experience using PHP to even hazard a guess. What i do know is it drove me up the wall for a week.