I have a PHP code (index.php) for searching keywords in two html files (data.html & data2.html). When I search a keyword, such as "Ann", would it be possible to parse both html files and shows the line matching the keyword (i.e. This is Ann.)? The source codes are as follows:
index.php
<?php
$search = $_GET['keyword'];
$data = file('data.html');
$check = false;
foreach($data as $match)
{
if(strpos($match, $search) !== false)
{
$check = true;
$output = '<div>'.$match.'<div>';
echo $output;
}
}
?>
data.html
This is Ann.
This is Bob.
This is Candy.
data2.html
This is Ann.
This is Peter.
This is Bob.
Many thanks for help.
You can use like that;
<?php
$search = $_GET['keyword'];
$data = file('data.txt');
$data2 = file('data2.txt');
$datas = Array($data, $data2);
foreach($datas as $index => $data){
foreach($data as $lineNumber => $match )
{
if(strpos($match, $search) !== false)
{
echo "<div><b>$index 'th file</b>. Line number: $lineNumber . Match: $match <br />";
}
}
}
?>
If you need read more than one file at the same time you just add like data3 and add also array too.
Related
$reply[$c] Contains "123 123 123" How can i convert so $reply[$c] equals 123\n123\n123
echo str_replace(' ',"\n",explode("\n", $reply[$c]));
My code that failed ^
Here is the code showing how $reply[$c] was formed and used im pretty new to php.
Quick code reference:
if (mysql_num_rows($result) > 0) {
//Fetch Results from Mysql (Store in an accociative array, because they wont be in the right order)
$rows = array();
while ($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
$rows[$row['id']] = $row;
}
//Call Sphinxes BuildExcerpts function
if ($CONF['body'] == 'excerpt') {
$docs = array();
foreach ($ids as $c => $id) {
$docs[] = "'".mysql_real_escape_string(strip_tags($rows[$id]['body']))."'";
}
$result = mysql_query("CALL SNIPPETS((".implode(',',$docs)."),'{$CONF['sphinx_index']}','".mysql_real_escape_string($q)."')",$sphinxql);
$reply = array();
while ($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
$reply[] = $row['snippet'];
}
}
foreach ($ids as $c => $id) {
$row = $rows[$id];
print ($reply[$c]); //Need to replace spaces with new lines here
}
}
Full code reference: http://nearby.org.uk/sphinx/search-example5-sphinxql.phps
You don't need to explode your string. Just replacing the spaces with newlines is enough.
echo str_replace(' ', "\n", $reply[$c]);
I have 2 array in my code, like the shown below:
<?php
$kalimat = "I just want to search something like visual odometry, dude";
$kata = array();
$eliminasi = " \n . ,;:-()?!";
$tokenizing = strtok($kalimat, $eliminasi);
while ($tokenizing !== false) {
$kata[] = $tokenizing;
$tokenizing = strtok($eliminasi);
}
$sumkata = count($kata);
print "<pre>";
print_r($kata);
print "</pre>";
//stop list
$file = fopen("stoplist.txt","r") or die("fail to open file");
$stoplist;
$i = 0;
while($row = fgets($file)){
$data = explode(",", $row);
$stoplist[$i] = $data;
$i++;
}
fclose($file);
$count = count($stoplist);
//Cange 2 dimention array become 1 dimention
for($i=0;$i<$count;$i++){
for($j=0; $j<1; $j++){
$stopword[$i] = $stoplist[$i][$j];
}
}
//Filtering process
$hasilfilter = array_diff($kata,$stopword);
var_dump($hasilfilter);
?>
$stopword contain of some stop word like attached in http://xpo6.com/list-of-english-stop-words/
All I wanna do is: I want to check if save the element that exist in array $kata and it is not exist in array $stopword
So I want to delete all the element that exist in both array $kata and $stopword .
I read some suggestion to use array_diff , but somehow it doesn't work to me. Really need your help :( Thanks.
array_diff is what you need, you are right. Here is a simplified version of what you try to do:
<?php
// Your string $kalimat as an array of words, this already works in your example.
$kata = ['I', 'just', 'want', 'to', '...'];
// I can't test $stopword code, because I don't have your file.
// So let's say it's a array with the word 'just'
$stopword = ['just'];
// array_diff gives you what you want
var_dump(array_diff($kata,$stopword));
// It will display your array minus "just": ['I', 'want', 'to', '...']
You should also double check the value of $stopword, I can't test this part (don't have your file). If it does not work for you, I guess the problem is with this variable ($stopword)
There is a problem in your $stopword array. var_dump it to see the issue.array_diff is working correct.
Try following code I wrote to make your $stopword array right:
<?php
$kalimat = "I just want to search something like visual odometry, dude";
$kata = array();
$eliminasi = " \n . ,;:-()?!";
$tokenizing = strtok($kalimat, $eliminasi);
while ($tokenizing !== false) {
$kata[] = $tokenizing;
$tokenizing = strtok($eliminasi);
}
$sumkata = count($kata);
print "<pre>";
print_r($kata);
print "</pre>";
//stop list
$file = fopen("stoplist.txt","r") or die("fail to open file");
$stoplist;
$i = 0;
while($row = fgets($file)){
$data = explode(",", $row);
$stoplist[$i] = $data;
$i++;
}
fclose($file);
$count = count($stoplist);
//Cange 2 dimention array become 1 dimention
$stopword= call_user_func_array('array_merge', $stoplist);
$new = array();
foreach($stopword as $st){
$new[] = explode(' ', $st);
}
$new2= call_user_func_array('array_merge', $new);
foreach($new2 as &$n){
$n = trim($n);
}
$new3 = array_unique($new2);
unset($stopword,$new,$new2);
$stopword = $new3;
unset($new3);
//Filtering process
$hasilfilter = array_diff($kata,$stopword);
print "<pre>";
var_dump($hasilfilter);
print "</pre>";
?>
I hope it helps
I have a document called subjects.txt in the following format:
DateCreated,Subject,Link
18.10.2015,"Math",http: //address.html
17.10.2015,"English",http: //address.html
18.10.2015,"English",http: //address.html
19.10.2015,"Science",http: //address.html
17.10.2015,"Math",http: //address.html
The file contains URLs of sites created based on a school subject. There can be more than one site for a subject.
The goal is to use PHP to open, read, and display the contents of the file in the following format:
Math
Link 1
Link 2
English
Link 1
Link 2
Science (because there's only one link, the name of the subject is the
link)
So far I've been able to open and read the file:
$file = "./subjects.txt";
$subjects = file_get_contents($file);
I'm having trouble trying to determine how to go about writing the file in specified format.
I've tried using explode to separate the elements with "," - however I don't know where to go from there.
Your input file looks to be in Comma-separated values (CSV) format. PHP has a built-in fgetcsv function designed to make reading CSV data from a file easy.
<?php
$file = './subjects.txt';
$fh = fopen($file, 'r');
if ($fh === false) {
die("Can not read {$file}");
}
$data = array();
while (($row = fgetcsv($fh, 1000, ',')) !== false) {
if ($row[0] === 'DateCreated') {
// Ignore the column header row
continue;
}
list($date, $subject, $link) = $row;
if (!isset($data[$subject])) {
$data[$subject] = array();
}
$data[$subject][] = $link;
}
fclose($fh);
foreach ($data as $subject => $links) {
// TODO: output each subject here
}
Here is another version
<?php
$file = "./subjects.txt";
$h = fopen($file, "r");
if($h !== false) {
$subjects = [];
$data = [];
while(!feof($h)) {
if($line = trim(fgets($h))) {
$line = explode(",", $line);
if(!in_array("DateCreated",$line)) {
array_push($subjects, $line);
}
}
}
fclose($h);
foreach ($subjects as $subject) {
if(!isset($data[$subject[1]])) {
$data[$subject[1]] = [];
}
$data[$subject[1]][] = $subject[2];
}
foreach ($data as $subject => $links) {
if(count($links) == 1) {
echo "<p>$subject</p>\n";
} else {
$i = 1;
echo "<p>$subject</p>\n";
echo "<ul>\n";
foreach ($links as $link) {
echo "<li>link$i</li>\n";
$i++;
}
echo "</ul>\n";
}
}
}
?>
The problem using file_get_contents() is that retrieves all the file contents into $subjects.
You have to use a different approach. For example fgets():
$fp = fopen("./subjects.txt", "r");
if ($fp){
while (($line = fgets($fp)) !== false){
// So here you can treat each line individually.
// You can use explode (";", $line) for example if the line is not empty
}
}
fclose($fp);
Using fgets() will allow you to parse each of the file's lines individually.
As stated doing this with a database would be much easier probably 3 lines of code. Here's one approach you could use though.
$data = '18.10.2015,"Math",http: //address.html
17.10.2015,"English",http: //address1.html
18.10.2015,"English",http: //address2.html
19.10.2015,"Science",http: //address3.html
17.10.2015,"Math",http: //address4.html';
preg_match_all('~^(.*?),"(.*?)",(.*?)$~m', $data, $fields);
array_multisort($fields[2], SORT_STRING, $fields[1], $fields[3]);
$lastcat = '';
foreach($fields[2] as $key => $cat) {
if($cat != $lastcat) {
echo $cat . "\n";
}
$lastcat = $cat;
echo $fields[3][$key] . "\n";
}
Output:
English
http: //address1.html
http: //address2.html
Math
http: //address4.html
http: //address.html
Science
http: //address3.html
The array_multisort is how the categories are grouped.
Here's a regex101 demo of what that regex is doing. https://regex101.com/r/wN3nB2/1
Update for single record check (only ran 1 test on it):
$data = '18.10.2015,"Math",http: //address.html
17.10.2015,"English",http: //address1.html
18.10.2015,"English",http: //address2.html
19.10.2015,"Science",http: //address3.html
17.10.2015,"Math",http: //address4.html';
preg_match_all('~^(.*?),"(.*?)",(.*?)$~m', $data, $fields);
array_multisort($fields[2], SORT_STRING, $fields[1], $fields[3]);
$lastcat = '';
foreach($fields[2] as $key => $cat) {
if((empty($fields[2][($key +1)]) && $cat != $lastcat)|| ($cat != $lastcat && !empty($fields[2][($key +1)]) && $fields[2][($key +1)] != $cat)) {
//single record
echo $cat . $fields[3][$key] . "\n";
} else {
if($cat != $lastcat) {
echo $cat . "\n";
}
$lastcat = $cat;
echo $fields[3][$key] . "\n";
}
}
I have a list of IDs
$Ids="1201,1240,1511,1631,1663,1666,1716,2067,2095";
and in the /imgs/ folder there are many jpg filenames related to these IDs. But there are a lot of IDs that do not have any image.
for example there are in the /imgs/
1201_73.jpg
1201_2897.jpg
1240-9834.jpg
1240-24.jpg
1511-dsc984.jpg
1511-dsc34.jpg
What I want to achieve is to find which of the IDs have images in the img folder.
Thank you
Updated
$array = array();
$foo = explode('.jpg', $images);
foreach($foo as $id) {
$digi = substr(trim($id), 0,4);
if(!in_array($digi, $array)) {
array_push($array, $digi);
echo $id . ".jpg <br/>";
$where .= "id='$digi' or ";
}
}
First, turn your string of IDs into an array.
$idsArray = explode(',', $Ids);
Now iterate through the directory, checking each file to see if it starts with the ID.
$hasImages = array();
foreach (new DirectoryIterator(__DIR__ . '/imgs') as $fileInfo) {
if ($fileInfo->isDot() || $fileInfo->isDir()) {
continue;
}
foreach ($idsArray as $id) {
if (0 === strpos($fileInfo->getBasename(), $id)) {
$hasImages[] = $id;
break;
}
}
}
$hasImages = array_unique($hasImages);
$hasImages will contain an array of IDs which have an image.
Something like this should work:
$files = glob('/imgPath/*.jpg');
$hasImage = array_unique(array_map(function($file) {
return explode('-', $file)[0];
}, $files));
$withimages= array_diff(explode($Ids), $hasImage);
I have a function in the controller that gets a string and then queries the database (via the model) for records that have this string as their name. This works fine with English but I have a problem when the input is in Hebrew. When I echo the string I see something like %D7%91 and the query fails.
All database tables entries are defined as utf8_general_ci.
My controller code:
function get_records_by_name($name)
{
echo 'searching for: '.$name.'</br>';
$keys = new DMkeys() ;
$query = $keys->get_keys();
$arr = array();
$count = 0;
foreach ($query->result() as $row)
{
if(stristr($row->name, $name) != FALSE)
{
$arr[] = $row->name;
$count++;
echo $row->name.'</br>';
}
}
$result = array('count' => $count, 'list' => $arr);
echo json_encode($result) ;
}
My model code:
function get_keys()
{
$query = $this->db->get('keys');
return $query;
}
Thanks,
Simon
You need to decode the variable before using it, try:
$name = urldecode($name);