search for the content of textarea1 in textarea2 - php

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?

Related

Php split text by line and get specific element

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

regex of two patterns

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

PHP while loop to read multiline text from string

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];
}

preg_match exact word and print out the entire line the result was found in

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);

How do I edit this text file using PHP?

I do have a text file having around 400k data in it. and its content is like this..
1,james
2,mathew
3,yancy
4,brandon
5,molner
6,nick
7,neil...and so on
How do I remove numbers and comas from this text file and keep only names?
Read the file into an array, where each array item is one line. Walk throught the array, find the first comma, and remove it and everything before. Then write it all back out again.
// Warning! Brain-compiled code ahead.
$arr = file('myfile.txt');
foreach ( $arr as &$val )
$val = substr($val, strpos($val, ',') + 1);
file_put_contents('myoutfile.txt', implode(PHP_EOL, $arr));
Note - no error checking. If a line lacks a comma, or comma is the last character, chaos ensues.
400k isn't incredibly much, so you should get away with this (tested):
foreach (file($path) as $line)
print preg_replace("~^[0-9]+\,(.*)~", "$1", $line);
Here is a perl one liner that do the job:
perl -i.save -pe 's/^\d+,//' test.txt
The original file will be saved in test.txt.save
This is tested and will return it as a list but you can save it to a database if you want:
$file_path='my_file.txt';
$file_handler = fopen($file_path, 'rt');
$doc = fread($file_handler, filesize($file_path)+1);
$rows = explode("\n", $doc);
$rows_array = array();
foreach ($rows as $row) {
$data = explode(",", $row);
$return_array[] = $data[1];
}
//print_r($return_array);
//you can save it to a db
echo '<ul>';
foreach($return_array as $value){
echo '<li>'.$value.'</li>';
}
echo '</ul>';

Categories