As you can see below, I'm attempting to extract the complete substring of an exploded array by using just a few characters to match the substring.
$keyword = array('Four Wheel', 'Power', 'Trailer');
function customSearch($keyword, $featurelistarray){
$key = ''; //possibly reset output
foreach($featurelistarray as $key => $arrayItem){
if( stristr( $arrayItem, $keyword ) ){
$termname = $key;
}
}
}
The array ($featurelistarray) comprises vehicle options, four wheel drive, four wheel disc brakes, power windows, power door locks, floor mats, trailer tow package, and many many more.
The point is to list all the options for a given category, and using the $keyword array to define the category.
I would also like to alphabetize the results. Thank you for the help!
To further explain, the $featurelistarray is exploded from a CSV field. The CSV field has a long length of options listed.
$featurelist=$csvdata['Options'];
$featurelistarray=explode(',',$featurelist);
$termname = $featurelistarray[0];
As you can see, $termname is assigned the first position of the exploded array. This was the original code for these features, but I need more control for $termname.
It seems to me you are trying to make database operations without database. I'd suggest to transform input into some kind of database.
Related
I am using php/mysql.
I am storing comma separated 6 digit numbers in text based column of table in database.
I want to get the method to find which numbers in given range are present in my database.
My table looks like :
|id|date|commaSeperatedList|
Now as input to sql I want to give a range of number (e.g 234101-234200).
Therefore I am expecting output to be in form of :
|id|date|number|
So, far the solution I have worked on is : Use of PHP's range function.
Using that I created a string based Long Where Clause.
foreach( $words as $word) {
$word=str_pad($word, 6, '0', STR_PAD_LEFT);
$whereClause .= ' commaSeperatedList LIKE "%' . $word . '%" OR';
}
Problem with it is that : I dont get to know exactly which were the numbers that were found common .
e.g lets say List has :
109001,234122,234123,345650
I am giving the range (234101-234200)
The above statement finds all rows that contain any number in provided range . However I also want to know which exact numbers were matched. In my provided example these numbers are : 234122,234123
So, expected output should be :
|1|date|234122|
|1|date|234123|
Any help in this regard will be appreciated.
Eventually had to store data by normalization.
There are queries(Full Text Match) that were doing the work but not only they were complex but slow as well.
As for me , Its always better to store data properly in normalized format. (Its not a space/time tradeOFF).
For others in similar situation . Do some extra work on data and store it properly.
Thanks everyone for valuable answers !
Try This Code May Help You to find between range
<?php
$list = "109001,234122,234123,345650";
$from = "234101";
$to = "234200";
$list = explode(",",$list);
foreach($list as $val)
{
if($val > $from && $val < $to)
{
echo $val."<br>";
}
}
?>
I have a string with values (which are suburbs) like so:
$suburbs = "Mawson, Elizabeth, Burnside, Elizbeth, Mawson";
There COULD be double ups in the suburbs that the string contains. I can't change this fact.
What I am trying to do is create an option list for a drop down menu that a user will use. I do not want to display the same suburb twice( or more for that matter).
What I have so far:
$suburbs = "Mawson, Elizabeth, Burnside, Elizbeth, Mawson";
//Explode the suburbs string delimited by a comma
$boom = explode(',', $suburbs);
foreach($boom as $b)
{
$suburbOptionList .= '<option value='.$b.'>'.$b.'</option>';
}
?>
<select> <?php
echo $suburbOptionList;
?>
</select>
I know that this will simply display all of the options but I really don't know how to display each suburb only once. Ive tried a few foreach,and if combinations but they look ugly and work just as bad.
Any help would be appreciated.
Cheers in advance!
Pass $boom through array_unique() and you'll be fine.
$bada_boom = array_unique($boom);
P.S.: This will not help if you have typos or variations in duplicates. (Elizbeth != Elizabeth).
In that case you will need to get creative.
Also, hw (in comments) made a good point about trimming whitespaces. If the suburbs come from an untrusted source and are improperly formatted, you may need to normalize them. This means trimming whitespaces and normalizing capitals:
$boom = array_walk($boom, 'trim');
$boom = array_walk($boom, 'strtolower');
$bada_boom = array_unique($boom);
I am working on a WordPress site where the client has uploaded thousands of photos to Flickr and now want me to move them all back into WordPress and associate them with there proper posts.
Even though there are thousands of images, there is really only about 50 unique images, all the other versions are the same image but uploaded to a different location on Flickr or a slightly different size or name.
In helping me track down all the unique images, based on a list like below, that part I have highlighted, I need to pull every record into a PHP array, the catch is the part I have highlighted, is what I want to make sure is UNIQUE among all records in the array.
Any help in taking an existing PHP ARRAy that has every record and making the array only show unique values based on that part of the Value string?
Is this a Regular Expressions use case?
If it used Regex or similar I think a pattern it could look for is /4485116555_ / followed by 10 digits and then followed up with a _
Appreciate any help in getting me 1 step closer to my goal, this is just 1 piece of the big puzzle.
http://farm5.static.flickr.com/4042/4485116555_19cc0eaa85.jpg
http://farm3.static.flickr.com/2703/4485767454_77476dbdd0.jpg
http://farm5.static.flickr.com/4008/4485116637_ff085b0ab2.jpg
http://farm5.static.flickr.com/4002/4485766896_af83d349c4.jpg
http://farm5.static.flickr.com/4037/4485766950_50d5739344.jpg
http://farm3.static.flickr.com/2785/4485116905_1fa0e2ea6c.jpg
http://farm5.static.flickr.com/4052/4704387613_77542dac2e.jpg
http://farm3.static.flickr.com/2734/4485767622_7b04c3bd3e.jpg
http://farm5.static.flickr.com/4037/4485767292_1a37fe6c57.jpg
http://farm5.static.flickr.com/4038/4485116955_f9c47672c3.jpg
http://farm5.static.flickr.com/4051/4485115681_6d7419a00b.jpg
http://farm3.static.flickr.com/2753/4485116095_30161a56bb.jpg
http://farm5.static.flickr.com/4123/4831194968_3977dff9dc.jpg
http://farm5.static.flickr.com/4054/4538941056_cda5a8242d.jpg
http://farm3.static.flickr.com/2091/4515081466_43cd1624ce.jpg
http://farm3.static.flickr.com/2684/4485766664_3bb9dd9c80_m.jpg
http://farm5.static.flickr.com/4010/4485115557_a38aac0e1f.jpg
http://farm5.static.flickr.com/4055/4485115633_19e6e92276.jpg
http://farm5.static.flickr.com/4045/4485766710_08691e99ed_m.jpg
http://farm5.static.flickr.com/4024/4485115521_9ab2a33d53_m.jpg
http://farm5.static.flickr.com/4048/4505577820_81ce080f2a_t.jpg
http://farm6.static.flickr.com/5294/5389182894_920a54ce97_m.jpg
http://farm5.static.flickr.com/4152/5073487038_5bdb9e3cbc_t.jpg
http://farm5.static.flickr.com/4024/4485115401_67a8957509_m.jpg
http://farm5.static.flickr.com/4062/4485766842_2209843592_m.jpg
$ids = array(); // Where we will keep our unique list of IDs
$lines = array(/* your list of URLs here */);
foreach ($lines as $line) {
preg_match(
'|^http://[A-Za-z0-9\\.]+/[0-9]+/([0-9]+)_[a-f0-9]+.*\\.jpg$|',
'http://farm5.static.flickr.com/4054/4538941056_cda5a8242d.jpg',
$matches
);
echo $matches[1]; // 4538941056
$ids[] = $matches[1]; // Push that into the IDs array
}
$ids = array_unique($ids);
print_r($ids);
Use this code to get your ID Portion
$url = 'Your image url';
$path = parse_url($url, PHP_URL_PATH);
$pathFragments = explode('/', $path);
$end = end($pathFragments);
$id = substr($end,0,9);
And then run array_unique() to get the unique values.
I have the following street names and house numbers in a text file:
Albert Dr: 4116-4230, 4510, 4513-4516
Bergundy Pl: 1300, 1340-1450
David Ln: 3400, 4918, 4928, 4825
Garfield Av: 5000, 5002, 5004, 5006, 8619-8627, 9104-9113
....
This data represents the boundary data for a local neighborhood (i.e., what houses are inside the community).
I want to make a PHP script that will take a user's input (in the form of something like "4918 David Lane" or "3000 Bergundy") search this list, and return a yes/no response whether that house exists within the boundaries.
What would be an efficient way to parse the input (regex?) and compare it to the text list?
Thanks for the help!
It's better to store this info in a database so that you don't have to parse out the data from a text file. Regexes are also not generally applicable to find a number in a range so a general purpose language is advised as well.
But... if you want to do it with regexes (and see why it's not a good idea)
To lookup the numbers for a street use
David Ln:(.*)
To then get the numbers use
[^,]*
You could simply import the file into a string. After this is done, breack each line of the file in an array so Array(Line 1=> array(), Line 2=> array(), etc. After this is done, you can explode using :. After, you'll simply need to search in the array. Not the fastest way, but it may be faster then regex.
You should sincerely consider using a database or re-think how your file are.
Try something like this, put your street names inside test.txt.. Now that you are able to get the details inside the text file, just compare it with the values that you submit in your form.
$filename = 'test.txt';
if(file_exists($filename)) {
if($handle = fopen($filename, 'r')) {
$name = array();
while(($file = fgets($handle)) !==FALSE) {
preg_match('#(.*):(.*)#', $file, $match);
$array = explode(',', $match[2]);
foreach($array as $val) {
$name[$match[1]][] = $val;
}
}
}
}
As mentioned, using a database to store street numbers that are relational to your street names would be ideal. I think a way you could implement this with your text file though is to create a a 2D array; storing the street names in the first array and the valid street numbers in their respective arrays.
Parse the file line by line in a loop. Parse the street name and store in array, then use a nested loop to parse all of the numbers (for ones in a range like 1414-1420, you can use an additional loop to get each number in the range) and build the next array in the initial street name array element. When you have your 2D array, you can do a simple nested loop to check it for a match.
I will try to make a little pseudo-code for you..
pseudocode:
$addresses = array();
$counter = 0;
$line = file->readline
while(!file->eof)
{
$addresses[$counter] = parse_street_name($line);
$numbers_array = parse_street_numbers($line);
foreach($numbers_array as $num)
$addresses[$counter][] = $num;
$line = file->readline
$counter++;
}
It's better if you store your streets in a separate table with IDs, and store numbers in separate table one row for each range or number and street id.
For example:
streets:
ID, street
-----------
1, Albert Dr
2, Bergundy Pl
3, David Ln
4, Garfield Av
...
houses:
street_id, house_min, house_max
-----------------
1, 4116, 4230
1, 4510, 4510
1, 4513, 4516
2, 1300, 1300
2, 1340, 1450
...
In the rows, where no range but one house number, you set both min and max to the same value.
You can write a script, that will parse your txt file and save all data to db. That should be as easy as several loops and explode() with different parameters and some insert queries too.
Then with first query you get street id
SELECT id FROM streets WHERE street LIKE '%[street name]%'
After that you run second query and get answer, is there such house number on that street
SELECT COUNT(*)
FROM houses
WHERE street_id = [street_id]
AND [house_num] BETWEEN house_min AND house_max
Inside [...] you put real values, dont forget to escape them to prevent sql injections...
Or you even can run just one query using JOIN.
Also you should make sure that your given house number is integer, not float.
Hey, basically what i am trying to do is automatically assign Tags to a user input string. Now i have 5 tags to be assigned. Each tag will have around 10 keywords. A String can only be assigned one tag. In order to assign tag to string, i need to search for words matching keywords for all the five tags.
Example:
TAGS: Keywords
Drink: Beer, whiskey, drinks, drink, pint, peg.....
Fitness: gym, yoga, massage, exercise......
Apparels: men's shirt, shirt, dress......
Music: classical, western, sing, salsa.....
Food: meal, grilled, baked, delicious.......
User String: Take first step to reach your fitness goals, Pay Rs 199 for Aerobics, Yoga, Kick Boxing, Bollywood Dance and more worth Rs 1000 at The very Premium F Chisel Bounce, Koramangala.
Now i need to decide upon a tag for the above string. I need an time efficient algorithm for this problem. I don't know how to go about matching keywords for strings but i do have a thought about deciding tag. I was thinking to maintain an array count for each tag and as a keyword is matched count for respective tag is increased. if at any time count for any tag reaches 5 we can stop and decide on that tag only this will save us from searching the whole thing.
Please give any advice you have on this. I will be using php just so you know.
thanks
Interesting topic! What you are looking for is something similar to latent semantic indexing. There is questing here.
If the number of tags and keywords is small I would save me writing a complex algorithm and simply do:
$tags = array(
'drink' => array('beer', 'whiskey', ...),
...
);
$string = 'Take first step ...';
$bestTag = '';
$bestTagCount = 0;
foreach ($tags as $tag => $keywords) {
$count = 0;
foreach ($keywords as $keyword) {
$count += substr_count($string, $keyword);
}
if ($count > $bestTagCount) {
$bestTagCount = $count;
$bestTag = $tag;
}
}
var_dump($bestTag);
The algorithm is pretty obvious, but only suited for a small number of tags/keywords.
If you dont mind using an external API, you should try one of these:
http://www.zemanta.com/
http://www.opencalais.com/
Benjamin Nowack: Linked Data Entity Extraction with Zemanta and OpenCalais
To give an example, Zemanta will return the following tags (among other things) for your User String:
Bollywood, Kickboxing, Koramangala, Aerobics, Boxing, Sports, India, Asia
Open Calais will return
Sports, Hospitality Recreation, Health, Recreation, Human behavior, Kick, Yoga, Chisel
Aerobics, Meditation, Indian philosophy, Combat sports, Aerobic exercise, Exercise