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");
}
}
?>
Link to comment
Share on other sites

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);
Edited by Ch0cu3r
Link to comment
Share on other sites

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?

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.