Adding to an empty array if word is found in two set of texts

Try removing or remming this line near the top of the script:

declare(strict_types=1); // PHP 7 ONLY

what text.txt file are you using?

doesn’t work

Isaiah 3 - Listen
10 Say ye to the righteous, that it shall be well with him: for they shall eat the fruit of their doings. Genesis 3 - Listen
1 Now the serpent was more subtil than any beast of the field which the LORD God had made. And he said unto the woman, Yea, hath God said, Ye shall not eat of every tree of the garden?
2 And the woman said unto the serpent, We may eat of the fruit of the trees of the garden:
3 But of the fruit of the tree which is in the midst of the garden, God hath said, Ye shall not eat of it, neither shall ye touch it, lest ye die.
5 For God doth know that in the day ye eat thereof, then your eyes shall be opened, and ye shall be as gods, knowing good and evil.
6 And when the woman saw that the tree was good for food, and that it was pleasant to the eyes, and a tree to be desired to make one wise, she took of the fruit thereof, and did eat, and gave also unto her husband with her; and he did eat.
11 And he said, Who told thee that thou wast naked? Hast thou eaten of the tree, whereof I commanded thee that thou shouldest not eat?
12 And the man said, The woman whom thou gavest to be with me, she gave me of the tree, and I did eat.
13 And the LORD God said unto the woman, What is this that thou hast done? And the woman said, The serpent beguiled me, and I did eat.
14 And the LORD God said unto the serpent, Because thou hast done this, thou art cursed above all cattle, and above every beast of the field; upon thy belly shalt thou go, and dust shalt thou eat all the days of thy life:
17 And unto Adam he said, Because thou hast hearkened unto the voice of thy wife, and hast eaten of the tree, of which I commanded thee, saying, Thou shalt not eat of it: cursed is the ground for thy sake; in sorrow shalt thou eat of it all the days of thy life;
18 Thorns also and thistles shall it bring forth to thee; and thou shalt eat the herb of the field;
19 In the sweat of thy face shalt thou eat bread, till thou return unto the ground; for out of it wast thou taken: for dust thou art, and unto dust shalt thou return.
22 And the LORD God said, Behold, the man is become as one of us, to know good and evil: and now, lest he put forth his hand, and take also of the tree of life, and eat, and live for ever: 

Please elaborate, “doesn’t work” isn’t enough information.
Like me saying “I just tried it and it works great” doesn’t help you much does it?

In what way is it not working?
What error messages are you getting?

1 Like

Please note that I have set the following in order to display any errors:

  error_reporting(-1); 
  ini_set('display_errors','1');


If there are errors please copy and paste the the reported errors.

You may also try reloading the online source file and copying and pasting the source code again.

How do you get out of this?

The way the code is written, the “text.txt” file needs to be in the same folder as the “keywords-test.php” file and needs to have “read” permission.

Ok but how do you get out of the source file mode? PHP7 is new to me.

I can’t figure out how to get the keywords from the url to the php:
<?php
/**
* John_Betong -Just testing date-stuff
*
* @package
* @subpackage
* @since
*/

    /*//declare(strict_types=1); // PHP 7 ONLY
    error_reporting(E_ALL);
    ini_set('display_errors', 'true');
    */
    $sp    = 'https://www.sitepoint.com/community/t/adding-to-an-empty-array-if-word-is-found-in-two-set-of-texts/217459/6';  
    $title = 'Adding an empty array if word is found in two set of texts';

    /*// DEBUG
      function fred($val, $title=NULL)
      {
        echo '<pre>';
          echo $title ? $title .' => ' :NULL;
          print_r($val);
        echo '</pre>';
      }*/
    // CLEAN INPUT  
      function clean($string) {
        $result = NULL;
        //$result = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
        //$result = str_replace(' ', ';', $string); // Replaces all spaces with semi-colons.
        $result = preg_replace('/[^A-Za-z0-9\-]/', '', $result); // Removes special chars.

        return $result;
      }

      // load data
        $sText = file_get_contents('text.txt');
        $aClrs  = array("red","blue","green","orange","purple","sienna","darkolivegreen","darkgreen","darkslateblue","navy","indigo","darkslategray","darkred","darkorange","olive","teal","slategray","dimgray","sandybrown","yellowgreen","seagreen","mediumturquoise","pink","gray","magenta","lime","cyan","deepskyblue","darkorchid","silver","paleturquoise","wheat","palegreen","lightblue","plum","black","#741b47","#351c75","#0b5394","#134f5c","#38761d","#bf9000","#b45f06","#990000","#a64d79","#674ea7","#3d85c6","#45818e","#6aa84f","#e69138","#cc0000","#c27ba0","#8e7cc3","#6fa8dc","#76a5af","#93c47d","#f6b26b","#e06666","#d5a6bd","#b4a7d6","#9fc5e8","#a2c4c9","#b6d7a8","#f9cb9c","#ea9999");

    // DEFAULT Search ?word=
      //$sWords = 'eat of the fruit';   
      //$sWords = $_GET['keywords'];
      //$sWords = $sWords;
      $sMsg   = 'Default Search: &nbsp; index.php?words='; 
      if( isset($_GET['keywords']) ):
        $sWords = $_GET['keywords'];
        $sMsg   = 'Search: ?words='.$sWords; 
      endif;
      $sWords = clean($sWords); // AND replace ' ' with '-'


    // fill arrays
      $aText  = explode(" ", $sText);
      //$aSrchs = explode("-", 'DUMMY-' .$sWords);  ' ' ESSENTIAL
      $aSrchs = explode(";", $sWords); // ' ' ESSENTIAL
      // fred($aSrchs, '$aSrchs'); // Eat of the fruit

      // associate different colours with each search word
        $aWordsToFind = array();
        foreach( $aSrchs as $id => $sSrc):
          $aWordsToFind[] = $sSrc;
        endforeach;  
        // fred($aWordsToFind);

    // step through $aText and fill aResults
      $aResult = array();
      foreach( $aText as $word ): // Say ye to the righteous
        $tmp = strtolower( clean($word) ); // AND replace ' ' with '-'
        if( $i2=array_search($tmp, $aWordsToFind) ):
          $sColor    = $aClrs[ --$i2 ]; // "red", "blue", "green", "orange",
          $aResult[] = '<b style="color:' .$sColor .';">' .$word .'</b>'; // .' | ' .$i2  
        else:
          $aResult[] = $word;      
        endif;  
      endforeach;

    $style = <<< STYLE
    body {background-color:#f8f8f8;}
    b    {font-size:1.1em;}
    .bdr {outline:solid 1px #aaa;} 
    .bg0 {background-color: #000; color:aqua;} 
    .bg3 {background-color: #eee;} 
    .bg2 {background-color: snow;}
    .cla {color:aqua;}
    .clb {clear:both;}
    .clg {color: darkgreen;} .clr {color:red;}
    .fll {float:left} .flr {float:right;}
    .fss {font-size:small;} .fs1 {font-size:1.42em;}
    .mga {margin:1em auto 2em;}
    .hg5 {min-height:5em;}
    .ooo {margin:0; padding:0;}
    .p42 {padding:0.42em;}
    .tac {text-align: center;}
    .w49 {width:47%;} .w88 {width:88%;}
    .wrp {word-wrap: break-word;}
    STYLE;

    ?><!DOCTYPE HTML>
    <html lang="en">
    <head>
      <title> <?=$title;?> </title>
      <meta charset="utf-8" />
      <meta name="viewport" content="width=device-width,initial-scale=1" >
      <style> <?=$style;?> </style>
    </head>
    <body class="ooo bg3 wrp">

    <?php
    /*  <div class="hg5 bg0 tac">
        <a href="<?=$sp;?>"><i class="flr fss cla XXXcla XXXfss">SitePoint</i> </a>
        <h1 class="ooo clb fs1"><?=$title;?></h1>
        <span class="clb fss"> <?=date("H:i:s");?> </span>
      </div> 
      
      <h5 class="ooo flr fss"> Scroll down for source </h5> 
      */
      ?>

      

      <h3 class="clb"> <?=$sMsg;?><?=$sWords;?> </h3>

      <div class="w88 mga bdr p42 bg2">
        <?php
        for($i=0; $i< count($aResult); $i++){
            echo $aResult[$i];
            }

          # Show Results
            foreach($aResult as $result):
              echo $result .' ';
            endforeach;
        ?>
      </div>

    <?php
    /*?>  <p class="clb">&nbsp;</p>
      <div class="w88 mga bdr p42 bg2">
          <em>Source file:</em>
          <hr>    
          <?php highlight_file(__FILE__);?>
      </div><?php */
    ?>

    </body>
    </html>

Why did you add rem statements?

Without errors enabled It is like programming with a blindfold. The error reporting is there not only to help you but also to be able to copy and paste any errors into this forum.

Please download the source files again and the test.txt file.

Run the dowloaded file again in your browser:

Edit:
Please also enclose all PHP script with:

three backticks
new blank line 
PHP script
new blank line
three backticks

i’m more familiar with the for loops than foreach loops.

I don’t understand this at all:
$aWordsToFind = array();
foreach( $aSrchs as $id => $sSrc):
$aWordsToFind = $sSrc;
endforeach;

The PHP Manual is really good and usually has a lot of examples:

http://php.net/manual/en/control-structures.foreach.php

Plesae let us know.If there is anything you don’t understand after trying the examples.

I have a hard time understanding what $id represents. And looked over the link you sent.

@gilgalbiblewheel

I have a hard time understanding what $id represents. And looked over the link you sent.

Actually it is not required in this version so try this instead:


 $aWordsToFind = array();
        foreach( $aSrchs as $sSrc):
          $aWordsToFind[] = $sSrc;
        endforeach;  
       

Edit:
It is hard work trying to edit using a tablet :frowning:

but how does that relate to foreach($aResult as $result):

@gilgalbiblewheel

but how does that relate to foreach($aResult as $result):

The original script required all the words saved into an array. The words could be highlighted with different colours.

Does the script now work in your browser?

yes it does. But when I change it to:

?keywords=pride,proud;kingdom;stablish; ever;throne;judgment;head;tail;peace;born;child;Philistines;David;heart;cut off;devour;destr;speak,spoke;judg;Jacob;Israel;brother; son;call;name

It doesn’t work.

Try this:

http://www.johns-jokes.com/downloads/sp-f/gilgalbiblewheel/index-jb-001.php?words=pride-proud-kingdom-stablish-ever-throne-judgement-head-tail-peace-born-child-philistines-david-heart-cut-off-devour-destr-speak-spoke-judg-jacob-israel-brother-son-call-name-wise-fruit-man

I will leave it up to your to change the hyphens to semi-colons :slight_smile:

but why replace semicolons with hyphens? Doesn’t it work as it is? I mean I used the semicolons to explode into an array.

And the reason I placed spaces in small words was so that it wouldn’t highlight them in bigger words, for example " son" and “person”.

On the other hand I don’t have any space after “child” to pick up on the mentionings of “children”.

I also don’t think think it’s turning out the way I asked. I asked for a list of words found in both texts in one array and a list of words not found in both texts in another array. HOWEVER, if a word like “pride” appears in both texts is sent to the array of words found, and “proud” isn’t found in both texts, than let it go in the array of words found along with “pride”.

I was able to write the code in the old php style except for the last part. Now that I updated to php7 I got lost.