$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']);
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'm new to php and have been using the community and answers here to really help me with a little project I'm working on so thank you all in advance for the help so far!
I am pulling a load of information held in a poorly formatted text file/feed, trimming the contents of special characters and then using str_replace to find other specific strings and replace them with commas(,) or semi-colons(;), in order to create a usable piece of text. I then want to search this text for certain keywords and return other parts of the text in it's place.
So far, I've managed to explode the text into a multidimensional array, but I can't work out how to search this array now, in order to pull out a specific piece of information. I'm essentially trying to build a searchable array that I can pull information from as and when the original feed updates. Here's a sample of the array as it stands at the moment:
Array
(
[0] => Array
(
[0] => 240
[1] => 1
[2] => euro
[3] => 2016-02-19 15:30:00
[4] => EUR
)
[1] => Array
(
[0] => 240
[1] => 3
[2] => euro2
[3] => 2016-02-19 15:00:00
[4] => EUR
)
[2] => Array
(
[0] => 1890
[1] => 9
[2] => uspb
[3] => 2016-02-17 22:59:00
[4] => USD
)
)
Essentially, I want to be able to write something that will search this array for say uspb (array 2, key 2) and if it is found, return the value held under another key. So if I want key 0, it will return 1890. If I want key 1 when searching for euro2 it will return "3".
I've looked through a ton of examples and nothing really fits what I'm after at the moment. Perhaps I'm looking at this the wrong way and using an array isn't the correct approach. Any advice would be greatly appreciated.
For reference, here's a copy of my code (slight redacted) so far.
<?php
$file=file_get_contents("http://www.example.com/feed/");
$trim=trim($file, "[]");
$find = array("{\"value\":\"", "\",\"date_utc\":\"", "\",\"currency\":\"");
$replace = array(",", ",", "");
$replaced = str_replace($find, $replace, $trim);
$ret = array_map (
function ($_) {return explode (',', $_);},
explode (';', $replaced)
);
print_r ($ret);
?>
As your array is multidimensional - you have to iterate over it to find the value you need:
foreach ($ret as $value) {
// the index you want to search is always `2`?
if ($value[2] == 'uspb2') {
echo $value[0];
break;
}
}
And moving to function:
function findMyValue(
$array,
$search_key,
$search_str,
$key
) {
foreach ($array as $v) {
if ($v[$search_key] == $search_str) {
return $v[$key];
}
}
return 'NOT_FOUND';
}
echo findMyValue($ret, 2, 'euro', 1); // outputs 3
echo findMyValue($ret, 2, 'uspb', 0); // outputs 1890
And as already noticed in comments - it's not a poorly formated text, it's JSON. You can get an array from JSON string simply with json_decode function:
$file=file_get_contents("http://www.example.com/feed/");
$ret = json_decode($file, true);
var_dump($ret);
I've looked and can't find a solution to this feature we would like to write. I'm fairly new to PHP so any help, advice and code examples are always greatly appreciated.
Let me explain what we want to do...
We have a block of HTML inside a string - the content could be up to 2000 words with styling such as <p>, <ul>, <h2> included in this HTML content string.
We also have an array of images related to this content inside a separate string.
We need to add the images from the array string into the HTML content at equal spaces without breaking the HTML code. So a simple character count won't work as it could break the HTML tags.
We need to equally space the images. So, for example; if we had 2000 words inside the HTML content string and 10 images in the array, we need to place an image every 200 words.
Any help or coding samples provided in order to achieve this is greatly appreciated - thank you for your help in advance.
You can use
$numword = str_word_count($str, 0);
for getting the number of row
or
$array = str_word_count($str,1);
for getting in $array an array with all the word (one for index) and then iterating on this array for rebuild text you need adding every number of time (word) the code for your image
This Sample is form php Manual
<?php
$str = "Hello fri3nd, you're
looking good today!";
print_r(str_word_count($str, 1));
print_r(str_word_count($str, 2));
print_r(str_word_count($str, 1, 'àáãç3'));
echo str_word_count($str);
?>
this is related result
Array
(
[0] => Hello
[1] => fri
[2] => nd
[3] => you're
[4] => looking
[5] => good
[6] => today
)
Array
(
[0] => Hello
[6] => fri
[10] => nd
[14] => you're
[29] => looking
[46] => good
[51] => today
)
Array
(
[0] => Hello
[1] => fri3nd
[2] => you're
[3] => looking
[4] => good
[5] => today
)
7
You can find it in this doc
for the insert you can try this way
$num = 200; // number of word after which inert the image
$text = $array[0]; // initialize the text with the first word in array
for ($cnt =1; $cnt< count( $array); $cnt++){
$text .= $array[$cnt]; // adding the word to the text
if (($cnt % $num) == 0) { // if array index multiple fo 200 insert the image
$text .= "<img src='your_img_path' >";
}
}
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
My original test implementation consisted of building an array of "ignore words" with the following code:
$ignoreList = array("test1", "test2", "test3");
Later on, I test for individual words in the $ignoreList:
if(in_array($word, $ignoreList)){
} else{
$words[$word] = $words[$word] + 1;
}
This code works perfectly - upon later echoing my word list, no words on the $ignoreList show up. I refactored to make it easier to add or remove words:
//Import ignore list
$ignore_raw = file_get_contents("includes/ignore.txt");
$ignoreList = explode("\n", $ignore_raw);
ignore.txt is a plain text file with each item on its own line, no spaces. The import and explode seems to be working, because a print_r statement on $ignoreList results in:
Array ( [0] => a [1] => and [2] => are [3] => as [4] => for [5] => in [6] => is [7] => more [8] => of [9] => than [10] => that [11] => the [12] => to [13] => with )
The comparison code, however, stops working properly, and words on the ignore list show up once again in my final results. Any ideas what's wrong?
Your ignore.txt file may have \r\n line endings, and your words actually have a trailing \r.
Try that:
$ignoreList = array_map('trim', file("includes/ignore.txt"));
BTW your code may be refactored like that:
$words = array_diff($words, $ignoreList); // removes ignored words
$words = array_count_values($words); // count words