This appears to be a simple task, but none of the previous posts quite addresses the nuances of this particular problem. I appreciate your patience with a new programmer.

I want to divide a text file (comments.txt) into arrays with the tilde as a divider. Then I want to pass a user string variable (nam) to the PHP and search for this string. The result should echo every whole array that contains the string anywhere inside of it.

For example:
Array ( [0] => hotdog [1] => milk [2] => dog catcher )

A search for "dog" would produce on screen: hotdog dog catcher

<?php

 $search = $_POST['nam'];
 $file = file_get_contents('comments.txt');
 $split = explode("~", $file);

 foreach ($split as $subarray)
 {
    if(in_array($search, $subarray))
    {
       echo $subarray;
    }
 }
?>

The simple task is now this embarrassing mess. If you are patient enough, could someone demonstrate the above code correctly? Thanks for your attention.

有帮助吗?

解决方案

Assuming you have 'comments.txt' and it contains something like:

hamburger~hotdog~milk~dog catcher~cat~dogbone

then this should work

$comments = file_get_contents("comments.txt");
$array = explode("~",$comments);

$search = "dog";
$matches = array();

foreach($array as $item){         // check each comment in array
    if(strstr($item, $search)){   // use strstr to check if $search is in $item
        $matches[] = $item;       // if it is, add it to the array $matches
    }
}
var_dump($matches);

其他提示

First, you might want to try using file() instead of file_get_contents(). This should do what you're looking for:

<?php
$search = $_POST['nam'];
$file = file('contents.txt');
$matches = array();
foreach ($file as $k => $v) {
    if ($a = explode('~', $v)) {
        foreach ($a as $possible_match) {
        if (preg_match('"/'. $search .'"/i', $possible_match)) {
            $matches[] = $possible_match;
        }
    }
}
print_r($matches);
?>

This method will allow you to maintain several different records (one in each line of the file) and interpret/process them independently.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top