Re: removing text from a string
| From: | Micah Gersten | Date: | Thu, 06 Nov 2008 00:46:58 +0000 |
| Subject: | Re: removing text from a string | ||
| References: | 1 2 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-282961@lists.php.net to get a copy of this message | ||
Ashley Sheridan wrote:
> On Wed, 2008-11-05 at 11:52 -0500, Wolf wrote:
>
>>>>>> 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);
>>>>>> }
>>>>>> ?>
>>>>>>
>>>>>>
>>>>> I'd go with a regular expression any day for something like this.
>>>>>
>> *groan*
>>
>> <?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. "
>> $findme=" ";
>> $pos=strpos($thedata,$findme);
>> $thedata_fixed=trim(substr($thedata,$findme));
>> //print the modified line and \n
>> echo $thedata_fixed."\n";
>> }
>> fclose($fp);
>> }
>> ?>
>>
>> See, no regex needed and no matter the size of the '######. ' it will always find
>> the first " " and then chop it from there to the end, then you trim it up and you get the
>> text.
>>
>> Wolf
>>
>>
> Thats a lot of code when a couple of lines and a regex will do ;)
>
>
> Ash
> www.ashleysheridan.co.uk
>
>
>
Yep, with a regex, it's real easy (untested code):
<?php
$fileData = file_get_contents("text,txt");
$newFileData = preg_replace('/^\d+?\.\s?(.*$)/m','/$1/', $fileData);
file_put_contents("newfile.txt", $newFileData);
?>
Thank you,
Micah Gersten
onShore Networks
Internal Developer
http://www.onshore.com