Jump to content

issue with outputting a text file..please help


zoomzoom9

Recommended Posts

i'm creating code where i am trying to open a text file, read each line, check to see if each line is a palindrome or not and then create a new text file displaying the original line of text as well as saying if it is a palindrome or not....here is my code. what am i doing wrong? please help!

 

 

<?php
 
$out = fopen('results.txt', 'a');
 
foreach (file('testPhrases.txt') as $line) {
$line = trim(str_replace('/[^a-zA-Z]+/', ' ', '', $line));
$reverse = strrev($line);
 
if ($line == $reverse){
echo fwrite($out, $line . "This is a palindrome.\n");
}
else{
echo fwrite($out, $line . "This is not a palindrome.\n");
}
}
?>

First str_replace does not take a regex pattern for the first  (search) argument and the subject string should be the third argument. You should use preg_replace instead for regex

$line = trim(preg_replace('/[^a-zA-Z]+/', ' ', $line));

Second you are echo'ing the result of fwrite, which is the number of bytes written. Not the text that was written. Change the if/else to

	$line .= " - This is " . (($line == $reverse) ? 'a' : 'not a') ." palindrome.\n"; // append this to current line
	echo "$line<br/>";
	fwrite($out, $line);

thanks for the help. i see what i was doing wrong now so thanks for the explanation too

 

it seems to be determining what is or is not a drome, but it is saying phrases aren't when they are. i think this is my line involving capital letters, punctuation and spaces. ('/[^a-zA-Z]+/', ' ', $line) did i not code that part right?

perhaps a matter of case-sensitivity, need to strtolower $line ? If that doesn't work, then post some example lines from your file.

 

ok so then how would i remove the punctuation and also remove the space so that a palindrome like \\ No trace; not one carton \\ would be recognized as a palindrome

replace with '' instead of ' ' so that all non-alpha chars are stripped.

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.