how to search for a string in text file using PHP - php

i have a php code that read TXT file and display its content.
i want to allow the user to make a search on any word he want and if its available the system will display it with the line number.
until now i was able to read the text and display it .
i know that i need to read it line by line and stored in variable right or it there any better options?
code
<?php
$myFile = "test.txt";
$myFileLink = fopen($myFile, 'r');
$myFileContents = fread($myFileLink, filesize($myFile));
while(!feof($myFileContents)) {
echo fgets($myFileContents) . "<br />";
}
if(isset($_POST["search"]))
{
$search =$_POST['name'];
$myFileContents = str_replace(["\r\n","\r"], "\n", $myFileContents);
if( preg_match_all('/('.preg_quote($search,'/').')/i', $myFileContents, $matches,PREG_OFFSET_CAPTURE))
{
foreach($matches[1] as $match)
{
$line = 1+substr_count(substr($myFileContents,0,$match[1]), "\n");
echo "Found $search on $line";
}
}
}
fclose($myFileLink);
//echo $myFileContents;
?>
<html>
<head>
</head>
<body>
<form action="index.php" method="post">
<p>enter your string <input type ="text" id = "idName" name="name" /></p>
<p><input type ="Submit" name ="search" value= "Search" /></p>
</form>
</body>
</html>

Something like this
$myFileContents = file_get_contents($myFileLink);
if( preg_match_all('/('.preg_quote($search,'/').')/i', $myFileContents, $matches)){
print_r($matches);
}
Using Preg match all, and case insensitive flag.
Getting the line number is much harder, for that you will want to do something like this:
$myFileContents = "Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident,
sunt in culpa qui officia deserunt mollit anim id est laborum.";
$search = "non proident";
//normalize line endings.
$myFileContents = str_replace(["\r\n","\r"], "\n", $myFileContents);
//Enter your code here, enjoy!
if( preg_match_all('/('.preg_quote($search,'/').')/i', $myFileContents, $matches,PREG_OFFSET_CAPTURE)){
foreach($matches[1] as $match){
$line = 1+substr_count(substr($myFileContents,0,$match[1]), "\n");
echo "Found $search on $line";
}
}
Outputs
Found non proident on 5
You can see it live here
If it's a large file you can do a similar search as you read each line. Something like this
$myFileLink = fopen($myFile, 'r');
$line = 1;
while(!feof($myFileLink)) {
$myFileContents = fgets($myFileLink);
if( preg_match_all('/('.preg_quote($search,'/').')/i', $myFileContents, $matches)){
foreach($matches[1] as $match){
echo "Found $match on $line";
}
}
++$line;
}

Related

PHP- Session lost upon refresh or revist

I'm new to php as you can tell and I'm having trouble with my session.Session is being lost upon refreshing page. I have a simple button that toggles between light and dark mode, it works and I store the value into a session value. I'm able to print the value and see that it is being stored, however upon a refresh or a revisit, the mode switches to the opposite mode and then upon refresh/revisit, the state is actually saved. I've tried to search for my issue but I cant find anything and I'm off to bed so I thought I may as well post in the meantime. I'm not sure what I'm missing, probably something obvious, but I appreciate the help. I can only use PHP for this by the way.
<?php
session_start();
//header('Refresh: 3000; url=index.php');
echo "" . $_SESSION['color'] . "";
echo "<body style = 'background-color: " . $_SESSION['color'] . ";'>";
?>
<!DOCTYPE html>
<html lang = "en-US">
<head>
<link rel="stylesheet" href="index.css">
<title>
Web Technologies
</title>
</head>
<body>
<?php session_start();
include_once "templateFunctions.php";
if (isset($_POST['dark'])) {
if (!isset($_SESSION['color'])) {
//session_register('color');
$_SESSION['color'] = "rgb(54, 53, 53)";
echo "<body style = 'background-color: " . $_SESSION['color'] . ";'>";
} else {
if ($_SESSION['color'] == "rgb(54, 53, 53)") {
$_SESSION['color'] = "white";
echo "<body style = 'background-color: " . $_SESSION['color'] . ";'>";
} else {
$_SESSION['color'] = "rgb(54, 53, 53)";
echo "<body style = 'background-color: " . $_SESSION['color'] . ";'>";
}
}
}
/*$color = "rgb(48, 48, 48)";
setcookie('color', $color, time() + 10, '/');
$_COOKIE['color'] = [$color];
echo "<p>'$cookie'</p>";
echo "<body style = 'background-color: $cookie;'>";
else {
$_SESSION['color'] = "rgb(54, 53, 53)";
echo "<body style = 'background-color: " . $_SESSION['color'] . ";'>";
}
*/
?>
<div class = "header">
<div class = "title" >
<h1>Jimbo Fimbo</h1><h2><u>Software Stuff</u></h2></th>
</div>
<div class = "img">
<img id = "img1" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTci5Mqm2mgMe_9KfJR0TqMEd-A_wtmqq69cru0wed7OEQF6jVAYycqCY_KzWV0o3hIVYs&usqp=CAU" alt="https://i.ytimg.com/vi/KEkrWRHCDQU/maxresdefault.jpg">
</div>
</div>
<hr style = "margin-bottom: 20px;">
<div class = "colgroup">
<div class="column1">
<h3 style = "text-align: center;">Menu</h3><hr style = "color:white;">
<ul style = "padding-left:20px; font-size: 25px;">
<li>GitHub<br></li>
<li>Courses<br></li>
<li>School<br></li>
</ul>
</div>
<div class="column2">
<h1>About Me</h1>
<img id = "img2"src="https://i.ytimg.com/vi/KEkrWRHCDQU/maxresdefault.jpg">
<p>
Heres some lorem ipsum! <br> Lorem ipsum dolor sit amet. Reprehenderit sunt est quia
necessitatibus est eius quis. Est dolor adipisci et dolor molestiae hic vitae expedita eum inventore quam aut mollitia natus. Qui quia
dolor aut totam Quis qui expedita repudiandae non quam magni et enim ipsa qui consequatur omnis. Ea incidunt debitis est nemo nesciunt
eum quia rerum eum recusandae sunt nam maiores saepe. Hic omnis dolores ab deserunt vero cum fugiat explicabo vel perferendis numquam.
Sed unde voluptatibus quo aliquid iure rem accusamus voluptatum aut maxime adipisci id molestiae voluptatem? In quia necessitatibus et
provident id nobis eius ea enim voluptatem in aliquam voluptas ut similique facilis. Et porro ipsam eos excepturi voluptatem non ullam sint.
</p>
<p>Stuff goes here </p>
</div>
<div class="column3">
<p style = "text-align: center;">Enrolled Courses</p>
<hr style = "color:white;">
<ol style = "padding-left: 20px; font-size: 25px;">
<li>CS-3753</li>
<li>CS-4393</li>
<li>CS-4413</li>
<li>CS-4423</li>
<li>CS-4843</li>
</ol>
<form action="index.php" method = "post" accept-charset=utf-8 >
<input type="submit" name = "dark" id ="submit" value = "Dark Mode">
</form>
</div>
</div>
<footer class="foot">
Copyright 2022, Jimbo Fimbo
</footer>
</body>
</html>
I'm expecting what I mentioned above.
I've looked over the code to no avail, I've tried using another session variable to save the color change, I tried saving the session to a path using said method, and I've looked on the internet for similar problems but I guess I suck at googling since this seems like it would be straightforward.
If you want to get rid of the problem that the session variable will be "toggled" on page refresh, One of the ways is to separate the change color part from your display part, so the form submission target can be set to "changecolor.php", which will trigger a page redirection to index.php upon changing the session variable :
index.php
<?php
session_start();
/// initalize the color to be white if no color session variable
if (!isset($_SESSION['color'])) {
$_SESSION['color'] = "white";
}
echo "<body style = 'background-color: " . $_SESSION['color'] . ";'>";
?>
/// other HTML code
<form action="changecolor.php" method = "post" accept-charset=utf-8 >
<input type="submit" name = "dark" id ="submit" value = "Change Color Mode">
</form>
changecolor.php
<?php session_start();
if (isset($_POST['dark'])) {
if (!isset($_SESSION['color'])) {
$_SESSION['color'] = "rgb(54, 53, 53)";
} else {
if ($_SESSION['color'] == "rgb(54, 53, 53)") {
$_SESSION['color'] = "white";
} else {
$_SESSION['color'] = "rgb(54, 53, 53)";
}
}
header("Location: index.php");
}
?>

How do I paginate json data in php

I have json data that looks like this
{
"project_no":1693,
"project_name":"Theresa Project",
"description":"Nonumy euismod ornatus usu te, quodsi viderer accommodare sea cu, ut alterum officiis nec. At deleniti eloquentiam vis. Explicari definitionem ei sea. No nec erat fugit voluptaria, in his elit discere fastidii. Aperiri virtute no eos. Te per habemus vulputate, partem iuvaret intellegebat eam in.",
"project_cost":10000.00,
}
{
"project_no":1664,
"project_name":"School Supplies for Children",
"description":"Nonumy euismod ornatus usu te, quodsi viderer accommodare sea cu, ut alterum officiis nec. At deleniti eloquentiam vis. Explicari definitionem ei sea. No nec erat fugit voluptaria, in his elit discere fastidii. Aperiri virtute no eos. Te per habemus vulputate, partem iuvaret intellegebat eam in. ",
"project_cost":8000.00,
},
I have over 60 records, With php I want to show 10 records on each page and dynamically populate the page numbers based on how many records I have.
Heres how I'm displaying the data.
$json = file_get_contents('http://linktojsondata.com');
$obj = json_decode($json, true);
<?php
$i = 0;
foreach ($obj as $project_name => $project_info) { ?>
<a href="single-project-detail.php/<?php echo $project_info['project_no'];?>">
<img class="img-thumbnail" alt="" src="<?php echo $project_info['featured_image_url']; ?>">
</a>
<a href="single-project-detail.php/<?php echo $project_info['project_no'];?>">
<?php echo $project_info['project_name']; ?>
</a>
<p>
<?php $string = strip_tags($project_info['description']);?>
</p>
<?php if (++$i == 10) break; } ?>
Here is a start, you will split the json array into blocks of 10 using array_chunk, and then loop through this using the page number $_GET['p'] - 1 so your page url may look like page.php?p=2 which will select the second set of data.
$pages = array_chunk(json_decode($json, true), 10, true);
foreach ($pages[$_GET['p'] - 1] as $project_name => $project_info) {
// your code
}

regex find <table> and modify

I have code on a side which looks like the one below and will be generated from a CMS.
The user can generate a table, but I have to put a <div> around it.
<p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et
dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo
dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem</p>
<table>
<thead>
<tr><td></td></tr>
...
</tbody>
</table>
<p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et
dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo
dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem</p>
<table>
<thead>
<tr><td></td></tr>
...
</tbody>
</table>
...
My goal is it now to give every <table> a <div class="table">
I´ve tried it with regex and got this result:
function smarty_modifier_table($string) {
preg_match_all('/<table.*?>(.*?)<\/table>/si', $string, $matches);
echo "<pre>";
var_dump($matches);
}
/* result
array(2) {
[0]=> string(949) "<table>...</table>"
[1]=> string(934) "<thead>...</tbody>"
}
array(2) {
[0]=> string(949) "<table>...</table>"
[1]=> string(934) "<thead>...</tbody>"
}
*/
First of all, I do not understand why the second array [1]=> string(934) "<thead>...</tbody>" appears
and second how to fit the modified array back into the string on the right place.
If your html is really simple like this, the following would probably work:
print preg_replace('~<table.+?</table>~si', "<div class='table'>$0</div>", $html);
If, however, you can have nested tables:
<table>
<tr><td> <table>INNER!</table> </td></tr>
</table>
this expression will fail miserably - that's why using regexes to parse html is not recommended. To handle complex html it's better to use a parser library, for example, XML DOM:
$doc = new DOMDocument();
$doc->loadHTML($html);
$body = $doc->getElementsByTagName('body')->item(0);
foreach($body->childNodes as $s) {
if($s->nodeType == XML_ELEMENT_NODE && $s->tagName == 'table') {
$div = $doc->createElement("div");
$div->setAttribute("class", "table");
$body->replaceChild($div, $s);
$div->appendChild($s);
}
}
This one handles nested tables correctly.
$buffer = preg_replace('%<table>(.*?)</table>%sim', '<table><div class="table">$1</div></table>', $buffer);
Thank you all for your incredible fast and perfect help!
So it works for me.
$result = preg_replace('~~si', "$0", $string);
return $result;
regards
Torsten

how to get first some line from a paragraph

I have a paragraph stored in database i want to get only first five line from . it how to do this ?
should i convert first array to srting ? if yes then how to do this ?
if its string than i can do this by
$str='mayank kumar swami mayank kumar swami';
$var= strlen($str);
for($i=0;$i<8;$i++){
echo $str[$i];
}
or how to get only 200 word from the database by sql ?
i know it can be done by css easily shows in Show first line of a paragraph nut i want to do this by php or sql query
what i doing
$article_result = mysql_query("SELECT * FROM article ORDER BY time DESC LIMIT 1",$connection);
if($article_result){
while($row = mysql_fetch_array($article_result))
{
echo "<div class=\"article_div\" >";
echo "<h4 id=\"article_heading\"><img src=\"images/new.png\" alt=\"havent got\" style=\"padding-right:7px;\">".$row['article_name']."</h4>";
echo"<h5 class=\"article_byline\">";
echo" by";
echo"{$row['authore']}</h5>";
echo" <div id=\"article_about\"><p>{$row['content']}</p></div>";
//here i want to get only 2000 word from database (content)
echo "</div>";
}
}
There are a number of solutions to this problem.
If you want to split it by number of words, something similar to what user247245 posted:
function get_x_words($string,$x=200) {
$parts = explode(' ',$string);
if (sizeof($parts)>$x) {
$parts = array_slice($parts,0,$x);
}
echo implode(' ',$parts);
}
My preferred method however is getting all the full words up until a certain point (e.g. 200 characters):
function chop_string($string,$x=200) {
$string = strip_tags(stripslashes($string)); // convert to plaintext
return substr($string, 0, strpos(wordwrap($string, $x), "\n"));
}
The above will chop the string at 200 characters, however will only chop it after the end of a word (so you won't get half a word returned at the end)
Are we talking words, lines or letters?
If words:
$a = explode(' ',$theText);
if (sizeof($a)>200) $a = array_slice($a,0,200);
echo implode(' ',$a);
regards,
You can use substring function in mysql
SELECT SUBSTRING('Quadratically',1,5);
returns
Quadr
I suggest you do with sql as it reduces the amount of data transfer between you db server and application server.
So, Now you modify to this
$article_result = mysql_query("SELECT article_name, authore, SUBSTRING(content,1,200) as content FROM article ORDER BY time DESC LIMIT 1",$connection);
Try This:
<?php
echo substr("mayank kumar swami mayank kumar swami", 0, 6);
?>
Result Output: mayank
<?php
$about_vendor ="Lorem ipsum dolor sit amet, consectetur adipisicing elit. Adipisci officia excepturi quisquam mollitia, obcaecati cupiditate, quaerat est quibusdam nostrum esse culpa voluptates eum, et architecto animi. Voluptates enim tenetur minus! Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laboriosam magni exercitationem non at error possimus, voluptas aut, aperiam sint pariatur illo libero vel aspernatur tempora laborum. Harum nesciunt quos at. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Vitae quidem saepe voluptates minus delectus, dolores, repellat maiores quae consectetur quasi qui voluptas eius odit autem optio cupiditate nesciunt iste ducimus!"
// Convert string to array
$convert_to_array = explode(' ',$about_vendor);
// Total length of array
$total_length_of_array = count($convert_to_array);
?>
<p class="tip_par" style="text-align:justify;">
<!-- specify how many words do you want to show, I like to show first 30 words -->
<?php for($i=0;$i<=30;$i++) {
echo $convert_to_array[$i].' ';
} ?>
<!-- If you have more than 30 word it will show on toggle click on below more link -->
<span style="color:#C1151B;"> <span data-toggle="collapse" data-target="#demo" style="cursor:pointer;"><?php if($total_length_of_array >30) {
echo "more";
} ?></span>
<div id="demo" class="collapse tip_par" style="padding-top: 0px;">
<?php for($i=31;$i<$total_length_of_array;$i++) {
echo $convert_to_array[$i].' ';
} ?>
</div>
</span> </p>

PHP - How can I retrieve and process all images and their parent anchor tags from a content block?

Note: I'm using Wordpress, but I don't believe it's relevant to the answer, so I've asked it on SO. If I'm wrong, please tell me/move the question.
Okay, I'm loading up blocks of rich content (via Wordpress) which frequently contain many images wrapped in anchor tags. I'd like to step through all of them in order to display them as a tags with their relevant imgs inside.
I've already found this handy bit of regex-powered code which gets me the images perfectly well:
// Get the all post content in a variable
$posttext = $post->post_content;
//$posttext1 = get_cleaned_excerpt();
// We will search for the src="" in the post content
$regular_expression = '~src="[^"]*"~';
$regular_expression1 = '~<img [^\>]*\ />~';
// WE will grab all the images from the post in an array $allpics using preg_match_all
preg_match_all( $regular_expression, $posttext, $allpics );
// Count the number of images found.
$NumberOfPics = count($allpics[0]);
// This time we replace/remove the images from the content
$only_post_text = preg_replace( $regular_expression1, '' , $posttext1);
/*Only text will be printed*/
// Check to see if we have at least 1 image
if ( $NumberOfPics > 0 )
{
$this_post_id = get_the_ID();
for ( $i=0; $i < $NumberOfPics ; $i++ )
{ $str1=$allpics[0][$i];
$str1=trim($str1);
$len=strlen($str1);
$imgpath=substr_replace(substr($str1,5,$len),"",-1);
$theImageSrc = $imgpath;
global $blog_id;
if (isset($blog_id) && $blog_id > 0) {
$imageParts = explode('/files/', $theImageSrc);
if (isset($imageParts[1])) {
$theImageSrc = '/blogs.dir/' . $blog_id . '/files/' . $imageParts[1];
}
}
?>
<img class="alignleft" src='<?php echo get_bloginfo('template_directory').'/timthumb.php?src=' . $theImageSrc . '&h=150&w=150'; ?>' height="150" width="150" alt=""/>
I'd really like to wrap that bottom img with the relevant parent a. Any help here would be greatly appreciated.
An example of the content to be searched might be:
<h5>
<a href="http://www.example.com/imagefoo.jpg">
<img class="size-thumbnail wp-image-4091 alignleft" src="http://www.example.com/imagefoo-150x150.jpg" alt="" width="150" height="150" />
</a>
</h5>
<h5>
<a href="http://www.example.com/Image-Bar.jpg">
<img class="wp-image-4087 alignleft" title="Image - Bar" src="http://www.example.com/Image-Bar-150x150.jpg" alt="" width="150" height="150" />
</a>
</h5>
<h5>
<a href="http://www.example.com/Image-Alphe.jpg">
<img class="wp-image-4090 alignleft" title="Image-Alpha" src="http://www.example.com/Image-Alpha-150x150.jpg" alt="" width="150" height="150" />
</a>
</h5>
<img class="size-thumbnail wp-image-4088 alignleft" title="EXAMPLE-image-150" src="http://www.example.com/EXAMPLE-image-150-150x150.jpg" alt="" width="150" height="150" />
<h5>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</h5>
<a href="http://www.example.com/insanely-long-permalink-created-as-if-by-a-madman-who-knows-no-bounds-of-shame/" rel="attachment wp-att-2780">
<img class="alignright size-thumbnail wp-image-2780" title="Exhibition Title: Image Name by Artist Person" src="http://www.example.com/wp-content/uploads/2011/12/ExtraordinaryImage-150x150.jpg" alt="Example UK | Exhibition: Image by Artist Person" width="150" height="150" />
</a>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
EDIT: Here's the working code based on my needs. It uses XPath, based on cHao's answer below. (For what it's worth, I found Tizag's webpage very useful as an XPath primer, alongside this EarthInfo page.):
// Get the all post content in a variable
$posttext = $post->post_content;
$document = DOMDocument::loadHTML($posttext);
$xpath = new DOMXPath($document);
$i = 0;
# for each link that has an image inside it, set its href equal to
# the image's src.
foreach ($xpath->query('//a/img/..') as $link) :
$img = $link->getElementsByTagName('img')->item(0);
$link_src = $link->getAttribute('href');
$link_title = $link->getAttribute('title');
$img_src = $img->getAttribute('src');
$theImageSrc = $img_src;
global $blog_id;
if (isset($blog_id) && $blog_id > 0) {
$imageParts = explode('/files/', $theImageSrc);
if (isset($imageParts[1])) {
$theImageSrc = '/blogs.dir/' . $blog_id . '/files/' . $imageParts[1];
}
}
?>
<a href="<?php echo $link_src; ?>" rel="lightbox[<?php echo $this_post_id; ?>]" title="<?php if ($link_title) {
echo $link_title;
} else { the_title(); } ?>" class="cboxElement">
<img class="alignleft" src='<?php echo get_bloginfo('template_directory').'/timthumb.php?src=' . $theImageSrc . '&h=150&w=150'; ?>' height="150" width="150" alt=""/>
</a>
<?php
endforeach;
?>
You'd be better off not trying to use regular expressions for finding the images. They suck at parsing HTML.
Instead, check out the DOMDocument and DOMXPath classes.
$document = DOMDocument::loadHTML($posttext);
$xpath = new DOMXPath($document);
# for each link that has an image inside it, set its href equal to
# the image's src.
foreach ($xpath->query('//a[/img]') as $link) {
$img = $link->getElementsByTagName('img')->item(0);
$src = $img->getAttribute('src');
# do your mangling of $src here, resulting in $href.
# for example...
$href = preg_replace('/-\d+x\d+(?=\.[^.]*$)/', '', $src);
$link->setAttribute('href', $href);
}
$fixed_html = $document->saveHTML();

Categories