Jump to content

string manipulation - pro needed.


kelphyr

Recommended Posts

Ok, I fetch lines from text files which I need to manipulate but I'm not sure how. I've been asking around but couldn't find a proper answer so that is why I'm asking here.

 

Let's say I've stored a string of text into a variable named $line

 

#1. I need to check if that line has "//" in it or if possible, if it starts with it. I tried a code with the function named strpbrk() but it created errors. Maybe that's not the right way to go at it... How would you do it?

 

#2. How would you about reading something separated by Commas like "this,that,and..." ?

 

I learn from other people's code so an example would very very appreciated.

Thank you very much for you cooperation.

Link to comment
https://forums.phpfreaks.com/topic/39069-string-manipulation-pro-needed/
Share on other sites

I didn't understand your second question- but maybe by giving an example you can make things clear?

 

For #1:

<?php
// $filename holds the file's name

$lines = array_map("trim", file($filename));

foreach ($lines as $num => $line)
{
if(strpos($line, "//") === 0)
	echo "line #".$num." Starts with a //";
}

?>

 

 

For question 2 maybe you are looking for the explode() function...

 

Orio.

1. http://fi2.php.net/manual/en/function.strpos.php

 

strpos($line, "//") will return 0 if line starts with // (some other integer if line contains it) and NULL if it doesn't

 

2. http://fi.php.net/split

 

with split(",",$line) will return an array of strings (separated by , in array)

 

EDIT: explode will work better for #2

http://fi.php.net/manual/en/function.explode.php

thanks, Orio

strpos($line, "//") will return 0 if line starts with // (some other integer if line contains it) and NULL if it doesn't

 

strpos will return FALSE if the string isn't found.  That is why Orio uses the triple = when determining if the double slash is in his string.

trying to like only echo the lines that dont start with "//" but it doesnt work it just echo bad line..

while (!feof($handle)) {
while($line = fgets($handle)){
	if(strpos($line, '//')==FALSE){
	// Then do nothing
	echo "<BR>BAD LINE<br>";
	}else{
	// Process the line
	echo $line . "<br>";
	}
}
}

 

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.