PHP substr and strpos with files

Hi there,
I have created a form that reads a text file using an external php when a selection is made and submitted using the form. I want the file in question to have all of its commas removed , I want to use substr and subpos using functions to do all of this so I can reuse later. I’m relatively new to php , this is throwing my off and any guidance or help would be really really appreciated. Code is below:

<?php
//linking table to form
$studentid=$_POST["id"];

//To print out student ID
echo "You have selected Student ID: $studentid <br />";


//define what the file equals to which is the students ID
$file = "$studentid.txt";

//Opening the selected files
$fileopen = fopen($file,'r') or die("Sorry, cannot open $file");
if($fileopen){
    
while (($buffer=fgets($fileopen,4096))!==false){
//    echo $buffer."<br/>";
}    
if(!feof($fileopen)){
    echo "Error:unexpected fgets() fail\n";
    
}    
fclose($fileopen);    
}

//remove all commas from txt file
$filearray=file("$studentid.txt");
$count=count($filearray);

    for($i=0; $i<$count; $i++){
        
    $startnum=0;
    $stringlength = strlen($filearray[$i]);
    $comma = strpos($filearray[$i], ",", $startnum);
    $array[$i][0] = substr($filearray[$i], $startnum, $comma);
	$j=1;

The end of your code seems to be missing, the for() loop never closes. Is that a problem when you posted, or the bit you haven’t done yet? I’m not sure why you are creating that array element on the last (posted) line, have I misunderstood the requirement?

Why would you want to do it the hard way, rather than using str_replace() to just replace all commas with nothing?

Hello , code isn’t finished apologies. Id rather know how to do it the hard way first and learn the easy way next. thanks for coming back to me too :slight_smile:

sorry for being awkward guys

what about this?..

while ($j<$count-1){
			$comma = strpos($filearray[$i], ",", $startnum);
			$comma2 = strpos($filearray[$i], ",", $comma+1);
			$sub = $comma2-$comma;
			$num = substr($filearray[$i], $comma+1, $sub -1);
			$startnum = $comma2;
			$array[$i][$j]= $num;
		
		$j++;
        }

OK, then the way I’d do it is like this pseudo-code:

read file contents into a string
find first comma in that string with str_pos, result in $comma
while ($comma) {
  remove comma from $content using substr
  find first comma with str_pos
  }
result is string without any commas

ok thank you ill try this :slight_smile:

Couldi do this or is this completely wrong?..

$content =  file_get_contents("B00.txt");
$positions = array();
$pos = -1;
while (($pos = strpos($content, $char, $pos+1)) !== false) {
    $positions[] = $pos;
}

$result = implode(', ', $positions);

print_r($result);

That code creates a list of where all the commas are, it doesn’t remove them from the string.

oh crap how would I remove them…

If you translate that pseudo-code I posted above, that should do it. As far as I can see, there’s very little to do, in fact it probably took a little longer to post it as pseudo-code than it did to post actual code.

echo substr_replace($content, '', $positions[]) . "<br />\n";

would that be alright…

I don’t think so. As I read the documentation for substr_replace, you can only pass an array of positions into the function if you also pass an array of strings, and it uses the first position against the first string, the second position against the second string, and so on.

Can I just confirm that, when you say you want to remove the commas from the string, you mean that if you start with a file containing “This, is a file, a very small file, not a big file.” you want to end up with a string containing “This is a file a very small file not a big file.”? I am wondering whether I am not getting exactly what you want to do.

No that’s it yes I want to be able to do that

Then convert the pseudo-code I posted above into actual PHP, and that should do it for you. There’s no need to create an array of positions, just remove the commas one at a time. When you’ve coded that, you basically have your own version of str_replace().

…??

$result = array();
$key = 0;
$file =fopen("B00636.txt, r ");

if($file) {
while (( $line = fgets($file)) ! ==false) {
$delimiter = ',';

$pod =0;
$comma =0;
$innerkey = 0;
$previous = 0;
$loops =0;
$nr_commas = substr_count($line, $delimiter);

while($loops <= $nr_commas) {
$comma = strpos($line, $delimiter,$comma);

$previous = $comma +1;
$pos =$comma +1;
$innerkey++;
$loops++;
$coma++;

please stop wrting pseudo questions like ...?? with pseudo, incomplete code as a base. you have the code, you have to test it, you have to determine errors, you have to make conclusions from your tests and post them as human readable sentences.

start reverse: write a test first - what would be the result if your code works?

<?php

$commas = '123,abc,def,,$%&/()=';
$nocommas = '123abcdef$%&/()=';

var_dump(removecommas($commas) === $nocommas); // commas will be removed if existent
var_dump(removecommas($nocommas) === $nocommas); // no commas, nothing is changed

after setting up your requirements, you can start with the implementation

<?php

/* copy everything that is not a comma to a new string */
function removecommas(string $string){
	$result = '';
	for($i = 0; $i < strlen($string); $i++){ // loop over characters
		$char = $string[$i];
		if($char !== ',') $result .= $char;
	}
	return $result;
}

$commas = '123,abc,def,,$%&/()=';
$nocommas = '123abcdef$%&/()=';

var_dump(removecommas($commas) === $nocommas); // commas will be removed if existent
var_dump(removecommas($nocommas) === $nocommas); // no commas, nothing is changed

do not forget comments. you may also want to test on edge-cases, like empty strings or strings with commas only.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.