1

I have the following list of words (myfile.txt) which I want to display using PHP:

 word1
 #word2
 word3

What I want to do is to skip those lines that start with # above.

Below is the PHP code I used to display the words. But I don't know how to skip the # word.

<?php
$fp = fopen('myfile.txt','r');

if($fp){
  while(!feof($fp)){
    $name = fgets($fp);
    $name = rtrim($name);
    $value = urlencode($name);
    if(strlen($name) > 0){
      echo "<option value=$value>$name</option>";
    }
  }
 }
?>
</select>
</td>

What's the way to achieve that?

neversaint
  • 60,904
  • 137
  • 310
  • 477

5 Answers5

2

Simply by extending the condition to:

if((strlen($name) > 0) && ($name[0] != '#')){

Take a look at php manual on strings - section String access and modification by character.

If you ever needed checking more complex strings (like // or --) you may implement your own startsWith($haystack, $needle) function or use:

  • substr($name, 0, 2) == '//'
  • strpos($name, '//') == 0
Community
  • 1
  • 1
Vyktor
  • 20,559
  • 6
  • 64
  • 96
2
...
$name = fgets($fp);
$name = rtrim($name);
$value = urlencode($name);

if( strpos($value, '#') === 0 ) { continue; }
else // your code with if (strlen ...)

For more info, read also this article: Check if variable starts with 'http'

Community
  • 1
  • 1
Snake Eyes
  • 16,287
  • 34
  • 113
  • 221
1

you can check with substr function

if (substr($value,0,1)=="#"){
// do nothing
}

hope this will sure help u.

liyakat
  • 11,825
  • 2
  • 40
  • 46
1

Use following

$fp = fopen('myfile.txt','r');

if($fp){
  while(!feof($fp)){
    $name = fgets($fp);
    $name = rtrim($name);
    $value = urlencode($name);
    if(strlen($name) > 0 && $name[0]!='#'){
      echo "<option value=$value>$name</option>";
    }
  }
 }

Sunil Verma
  • 2,490
  • 1
  • 14
  • 15
1

You can do that as below:

$f = file("myfile.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

foreach ($f as $l) {
    if (strpos($l, '#') === 0)
        continue;
    $line = htmlspecialchars($l);
    echo "<option value=\"" . addslashes($line) . "\">$line</option>\n";
}
Manu Manjunath
  • 6,201
  • 3
  • 32
  • 31