2

I have following text after reading a file:

06/16/2011 04:01:05 AM : Process Start
06/16/2011 04:01:05 AM : Creating File
06/16/2011 04:01:05 AM : Opening File
06/16/2011 04:01:05 AM : Writing Text
06/16/2011 04:01:05 AM : Closing File
06/16/2011 04:01:05 AM : Sending File in email
06/16/2011 04:01:05 AM : Process End

I want to remove date and time in the beginning of each line like this:

Process Start
Creating File
Opening File
Writing Text
Closing File
Sending File in email
Process End

How can we do this with string matching technique ?

Thanks

1
  • Split each line of string (using AM or PM as condition) into 2 parts and pick the second part Commented Jun 16, 2011 at 9:58

6 Answers 6

5

One way to do this would be the following: (assuming the prefix is always the same length)

$output = '';
$tmp    = explode("\n",$input);

foreach($tmp as $t)
    $output .= substr($t,25)."\n";

echo $output;

First you explode the input into a variable by splitting it on every new line, and then for each line you remove the first 25 characters to create a new output.

http://codepad.org/ewuecNuU

Sign up to request clarification or add additional context in comments.

Comments

2

Date and time have constant length in your file. Use substr function to cut off 25 symbols from start of each line.

3 Comments

How to get each line separately and process it ??
@Student, if you look at my explanation I've provided code to do what IvanGL describes here.
use explode function: $lines = explode("\n", $text);
2

If all strings are prefixed with text of the same length, use substring. If not, use regular expression matching.

Comments

2

According to your example it seems that the best thing is to use substr() because the size of the prefix is always the same. But if you really need a matching technique it will look something like this:

$new_line = preg_replace('^/\d{2}\/\d{2}\/\d{4}\/ \d{2}:\d{2}:\d{2}\/ (?:AM|PM) : /', '', $line);

Comments

1
echo preg_replace('/(.*): /', '', $input);

3 Comments

It is good but it is not working correctly when there is another : in message after first :
yes, but your question does not provide that information. Use karolis more verbose answere then.
Yes. Therefore I up-voted you.. But my actual file contains extra :. Anyway Thanks...
1
$str = "text : to : remove :  text to keep";
$pos = strrpos($str, ":");
$str2 = substr($str, $pos+1);
echo $str2;

edit: changed strpos to strrpos, to find the last occurrence, as per comment below

1 Comment

This wouldn't work, there's : in the date as well, plus this would remove the ability to have : in the "text to keep".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.