getButterfly Logo getButterfly

I had this assignment the other days where I had to search for an existing string inside a text file – can also be an XML or CSV file – and I ended up searching inside a string (a WordPress option string – get_option('my_huge_string')).

Here’s how I did it:

<?php
$search = 'ciprian';

// Read from file
$lines = file('candidates.txt');
foreach($lines as $line) {
	// Check if the line contains the string we're looking for, and print if it does
	if(strpos($line, $search) !== false)
		echo '<h3>SEARCH RESULTS FOR: ' . $search . '</h3>' . $line . '<hr>';
}
?>

After changing it to searching inside a string, I had to modify it to work.

<?php
$search = 'ciprian';

// Read from file
$lines = nl2br($my_huge_string);
foreach($lines as $line) {
	// Check if the line contains the string we're looking for, and print if it does
	if(strpos($line, $search) !== false)
		echo '<h3>SEARCH RESULTS FOR: ' . $search . '</h3>' . $line . '<hr>';
}
?>

If using it inside WordPress, you can also lose the foreach() loop and use it directly:

<?php
$search = 'ciprian';

// Read from file
$lines = nl2br($my_huge_string);

// Check if the line contains the string we're looking for, and print if it does
if(strpos($line, $search) !== false)
	echo '<h3>SEARCH RESULTS FOR: ' . $search . '</h3>' . $line . '<hr>';
?>

Note: Use stripos() for case-insensitive searches.


Subscribe to getButterfly Blog

Once a week or so we send an email with our best content. We never bug you, we just send you our latest piece of content.



If you found any value in this post, agree, disagree, or have anything to add - please do. I use comments as my #1 signal for what to write about. Read our comment policy before commenting! Comments such as "Thank you!", "Awesome!", "You're the man!" are either marked as spam or stripped from URL.

Leave a reply