Search code examples
phpnewlinestrpos

I cannot get strpos to work with newline


I am very new to php and cannot find out how to fix this. I have a form and want to pass some string to it and have it checked with another file. It is working fine if all the strings are on the same line but as soon as I put in multiple lines of string, it will fail.

I have a php file with the following code:

<?php
echo "<center><form method='post' enctype='multipart/form-data'>";
echo "<b></b><textarea name='texttofind' cols='80' rows='10'></textarea><br>";
echo "<input name='submit' type='submit' style='width:80px' value='Run' />";
echo "</form></center>";

$texttofind = $_POST['texttofind'];
if(get_magic_quotes_gpc()) {
    $texttofind = stripslashes($texttofind);
}
$texttofind = html_entity_decode($texttofind);
$s = file_get_contents ("/home/xxxxx/public_html/abc.txt");
if (strpos ($s, $texttofind) === false) {
    echo "not found";
}
else
    echo "found";
?>

and in abc.txt, I have

dog  
cat  
rat

Whenever, I open the php page and type in just dog or cat, it will be fine and show 'found' message but when I type multiple lines like 'dog<enter on keyboard>cat' and click submit button, it will return with the 'not found' message.

What is wrong with the code or anyway to adapt it so that it will be able to search multiple lines?

Thank you in advance.


Solution

  • <?php
    $values=explode("\n",$txttofind);
    foreach($values as $value)
    {
        if (strpos ($s, $value) === false)
        {
            echo "$value : not found <br>";
        }
        else
        {
            echo "$value : found <br>";
        }
    }
    ?>