RE: removing text from a string

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



> -----Original Message-----
> From: Adam Williams [mailto:awilliam@xxxxxxxxxxxxxxxx]
> Sent: Tuesday, November 04, 2008 8:04 AM
> To: PHP General list
> Subject:  removing text from a string
> 
> I have a file that looks like:
> 
> 1. Some Text here
> 2. Another Line of Text
> 3. Yet another line of text
> 340. All the way to number 340
> 
> And I want to remove the Number, period, and blank space at the
> begining
> of each line.  How can I accomplish this?
> 
> Opening the file to modify it is easy, I'm just lost at how to remove
> the text.:
> 
> <?php
> $filename = "results.txt";
> 
> $fp = fopen($filename, "r") or die ("Couldn't open $filename");
> if ($fp)
> {
> while (!feof($fp))
>         {
>         $thedata = fgets($fp);
>         //Do something to remove the "1. "
>         //print the modified line and \n
>         }
> fclose($fp);
> }
> ?>

http://www.regular-expressions.info

<?php
  $fp = fopen($filename, "r") or die("Oh! The humanity!");

  if($fp) {
    while(!feof($fp)) {
      $thedata = preg_replace('/^\d+\.\s/', '', fgets($fp));
      echo $thedata . '\n';
    }

    fclose($fp);
  }
?>

Hints:
* "^" is the beginning-of-line marker in RegEx. (Usually.)
* "\d+" is compound:
  - "\d" is the "digit" marker. (0-9)
  - "+" after it means "one or more".
* "\." is just a period, but needs to be "escaped" in RegEx because it
has special meaning.
* "\s" is whitespace.
* "/" surrounding the pattern are just delimiters. They are not part of
the pattern itself.

HTH,


Todd Boyd
Web Programmer

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux