Jump to content

[SOLVED] String operations


robbyc

Recommended Posts

I currently have a string from which I want to remove common words which are stored in a text file.

 

If I create the array myself in PHP using the following code it works.

 

$commonWords = array (
		' The ',
		' How ',
		' Who ',
		' Why ',
		' More ',
		' In ',
		' A ',
		' An ',
		' To ',
		' I ',
		' It ',
		' At '
	);

foreach ($commonWords as $commonWord) {
		$string = str_ireplace($commonWord, ' ', $string);
	}

 

If I create the array from a text file using the following code it does not work.

 

$commonWords = array();

	$fileName = 'common.txt';

	if($file = fopen($fileName, 'r'))
	{
		$i = 0;
		while (!feof($file)) {
			$word = ' '.fgets($file).' ';
			$commonWords[$i] = $word;
			$i ++;
		}
	}

foreach ($commonWords as $commonWord) {
		$string = str_ireplace($commonWord, ' ', $string);
	}

 

The only difference I can see is that if I print_r both arrays the array created from the text file is double spaced.

 

Array

(

    [0] =>  The

 

    [1] =>  of

 

    [2] =>  and

 

    [3] =>  to

 

    [4] =>  a

 

    [5] =>  in

 

    [6] =>  that

 

    [7] =>  is

 

    [8] =>  was

 

    [9] =>  He

 

    [10] =>  for

 

    [11] =>  it

)

 

as opposed to the other array which is as follows.

 

Array

(

    [0] =>  The

    [1] =>  How

    [2] =>  Who

    [3] =>  Why

    [4] =>  More

    [5] =>  In

    [6] =>  A

    [7] =>  An

    [8] =>  To

    [9] =>  I

    [10] =>  It

    [11] =>  At

)

 

Can someone shed any light on what I am doing wrong. Also I am open to suggestions of a better way to do this.

 

Thanks in advance

 

Link to comment
https://forums.phpfreaks.com/topic/37537-solved-string-operations/
Share on other sites

It looks like fgets($file) is pulling the line endings along; use trim().

 

Also, you do not need the $i counter; you can do this: $commonWords[] = '...';

 

P.S. " The " will not be replaced if it is at the beginning of a line, for these specifics you'll need regex.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.