I have a very large csv list, I've already converted a list into array and managed to fix a problem I was having with UTF8:
$lines = file(''.get_template_directory_uri() . '/lines.csv');
foreach ($lines as $line_num => $line)
{
if(mb_detect_encoding($line, 'utf-8', false)) {
$listLines.= $line . '<br />';
}
}
But all of the list items follow one of the two patterns below:
Fist
Adolfo (São Paulo)|Adolfo (SP)
Basically I need all content that is before |, output:
Adolfo_(São_Paulo)
second
other items in the list do not have |
Abatiá (PR)
Abel Figueiredo (PA)
São Francisco de Assis do Piauí (PI)
I need output:
Abatiá
Abel_Figueiredo
São_Francisco_de_Assis_do_Piauí
I believe I'm going to have to use regex, but I'm a bit confused as to make the rule for both situations.
Based on comments... how about this:
$lines = file(''.get_template_directory_uri() . '/lines.csv');
foreach ($lines as $line_num => $line)
{
if(mb_detect_encoding($line, 'utf-8', false)) {
$exp = '';
if(strpos($line, '|')!==FALSE){
$exp = '/^(.+?)\s*\|/';
}else{
$exp = '/^(.+?)\s*\(/';
}
preg_match($exp, $line, $matches);
if($matches){
$line = $matches[1];
$line = preg_replace('/\s+/', '_', $line);
$listLines.= $line . '<br />';
}
}
}
Check if "|" is present in the string. If it is present then split on the bar and get only the 1st substring. If its not present then split on spaces and get all substrings except the last one.
This should work for your list of data if the elements belong to either of the types mentioned and there are no 3rd type of strings
Related
I have a big text file, split by new lines and on every line elements split by ';', like this:
1;1;20;3.6;0%;70%;25%;0%;5%;
1;2;80;4;45%;20%;20%;15%;0%;
1;3;80;4;40%;35%;5%;20%;0%;
1;4;20;3.6;15%;40%;38%;5%;2%;
1;5;20;3.6;30%;18%;33%;20%;0%;
1;6;80;4;27%;47%;23%;3%;0%;
What I would like to do is with PHP is to read the file correctly and access a specific element in any row, for example on row 2, element 3 (maybe, [1][2], if considered as indexes) and print it.
<?php
//split by new line
$text = fopen("public/data/data1.txt", "r");
if ($text) {
while (($lines = fgets($text)) !== false) {
//split by ;
$line = explode(';', $lines);
//access a specific element
}
fclose($text);
} else {
// error opening the file.
}
?>
Does somebody know how I could access this elements?
You can explode the string twice.
First on lines, then on ;.
$arr = explode(PHP_EOL, $str);
Foreach($arr as &$line){
$line = explode(";", $line);
}
https://3v4l.org/5fbvZ
Then echo $arr[1][2]; will work as you wanted
I have a multiline string and that have 2 words in line.
I want within a while loop while reading the script line by line
get the 1st word and 2nd word.
$multilinestring="name1 5
name2 8
name3 34
name5 55 ";
The result i want to have while i am reading the the string line by line is to get
2 more strings
$firstword and $secondword
Thank you all in advance!
Use this:
$eachLine = explode(PHP_EOL, $multilinestring); // best practice is to explode using EOL (End Of Line).
foreach ($eachLine as $line) {
$line = explode(" ", $line);
$firstword = $line[0];
$secondword = $line[1];
}
What's the point in using a while loop to do this? Use foreach loop to achieve this:
foreach (explode("\n", $multilinestring) as $line) {
$line = explode(" ", $line);
print_r($line);
}
If this is really a text file you want to read, then you'd be better of to use fgets() or read the file to an array completely with file() and use explode() afterwards. Consider this code:
$arr = file("somefile.txt"); // read the file to an array
for ($i=0;$i<count($arr);$i++) { // loop over it
$tmp = explode(" ", $arr[$i]); // splits the string, returns an array
$firstword = $tmp[0];
$secondword = $tmp[1];
}
how i can search for the content of textarea1 in textarea2 and print the whole line matches
example:
textarea1 contents(words)
content1
content2
content3
textarea2 contents(the lines)
this is content1
this is cont
this content3
so i want the printed matches lines like this
this is content1
this content 3
because content1 and content 3 in my textarea1
Here comes an example using preg_match(), note that the search strings have to be quoted by preg_quote():
$text1 = $_POST['text_area1'];
$text2 = $_POST['text_area2'];
// split search texts. in this case we use new line
$search = explode("\n", preg_quote($text1));
// now prepare for a regex
$regex = '~(' . implode('|', $search) . ')~';
// now split the text by newline
$lines = explode("\n", $text2);
foreach($lines as $line) {
if(preg_match($regex, $line)) {
print $line . "\n";
}
}
Output:
this is content1
this content3
Note that you may refine the way how you separate the search strings. In my example I split them by newline, but you may wish them additionally splitted by spaces or , ...
$textarea1 = "content1\ncontent2\ncontent3";
$chunks = explode("\n", $textarea1);
$textarea2 = "this is content1\nthis is cont\nthis is content3";
$lines = explode("\n", $textarea2);
foreach ($chunks as $c)
foreach ($lines as $l)
if (strpos($l, $c))
echo $l . '<br>';
To use regex in this case is a bit too much in my opinion, just use basic string-functions offered by php:
// the \n is the line break smybol used in the textarea
$needle = "content1\ncontent2\ncontent3"; // this text is probably received via $_GET['text1'] or something similar
$haystack = "this is content1\nthis is cont\nthis is content3";
// get all lines
$needle_lines = explode("\n", $needle);
$haystack_lines = explode("\n", $haystack);
foreach($haystack_lines as $hline) {
foreach ($needle_lines as $line) {
if (strpos($hline, $line) === false)
continue;
echo $hline."<br />";
//continue the outer foreach since we already found a match for the haystack_line
continue 2;
}
}
Update #1:
This code iterates through all lines in your haystack and checks for every needle in it.
If it finds one needle the line is printed via echo and we proceed with the next line of the haystack - is there anything more needed?
I'm using preg_replace to search for a word match within a line of a text file. If it is found, I would like to replace the entire line. My current problem is what I've tried thus far only replaces the exact word and not the entire line.
PHP
$database = "1.txt";
$id = "OFFENSIVEWORD1";
$str = file_get_contents($database);
$str = preg_replace("/\b".$id."\b/","********",$str);
$fp = fopen($database,'w');
fwrite($fp,$str);
fclose($fp);
1.TXT FILE
LOVING YOU MY FRIEND etc.
OFFENSIVEWORD1 YOU MY FRIEND etc.
OFFENSIVEWORD2 YOU MY FRIEND etc.
OFFENSIVEWORD3 YOU MY FRIEND etc.
EXPECTED OUTPUT
LOVING YOU MY FRIEND etc.
********
OFFENSIVEWORD2 YOU MY FRIEND etc.
OFFENSIVEWORD3 YOU MY FRIEND etc.
Thanks.
you need to change
$str = preg_replace("/\b".$id."\b/","********",$str);
to
$str = preg_replace("/\b" . $id . "\b.*\n/ui", "********\n", $str);
to make it work. Look out for the difference between newline among different operating systems.
update
or better use
$str = preg_replace("/.*\b" . $id . "\b.*\n/ui", "********\n", $str);
in case your offensive word is not in the start of the line.
This should do it as well (this is tested and works):
<?PHP
$str = "
hello this is PROFANE 1
clean statement";
$lines = explode('
', $str);
$newfile = '';
foreach($lines as $line) {
// ** change PROFANE 1 and PROFANE 2 obviously to real profane words to filter out
if (stripos($line, 'PROFANE 1') !== false || stripos($line, 'PROFANE 2') !== false) {
$line = preg_replace("/./", "*", $line);
}
$newfile .= '
' . $line;
}
echo "<pre>" . $newfile . "</pre>";
?>
i'm having a hard time understanding how to do this.
I want to search for a word, and then I want the search to return the word along with all the contents on the line the word was found in.
The word needs to be case sensitive so searching for TOM will not return Tom along with the results.
this is what I have tried thus far.
$contents = file_get_contents($file);
$pattern = preg_quote($word, '/');
$numInt = 0;
$pattern = "/^.*$pattern.*\$/m";
if(preg_match_all($pattern, $contents, $matches))
{
$numInt = count($matches[0]);
}
When I run this through my function it returns the results I want, but I noticed that it isn't consistant across different keyword.
In my text file for testing I have INT (x18) and my function returns 18 as the count. But if I use the keyword MORNING (x29) the function returns 31 which is technically correct because there are 2 instances where morning is used.
Well you could avoid using regex all together for this task.
Here's some code I whipped up:
<?php
$contents = file_get_contents($file);
#standardise those line endings
$contents = str_replace(array("\r","\r\n","\n\r","\n"),"\n",$contents);
$lines = explode("\n", $contents);
#find your result
$result = $line_num = array();
foreach($lines as $line_num => $l)
if(strpos($l, $word)) {
$result[] = $l;
$line_nums[] = $line_num;
}
echo "<pre>";
print_r($result);
echo "<br>Count:".count($result);