Remove some content from data php regx

62
July 20, 2018, at 07:20 AM

I want remove (deleted)345345 from the data file. number can be anything.

abc@gmail.com (deleted)395343
aab@gmail.com (deleted)2342322

i want data like eg. abc@gmail.com

Answer 1
<?php
$data = 'abc@gmail.com (deleted)395343' . PHP_EOL
      . 'aab@gmail.com (deleted)2342322';
$cleaned = preg_replace('/^([^\s]+).+$/m', '$1', $data);

In the above example we keep everything at start of the line until the first white-space in a capture group that replaces the whole line with our match.

But with big files, this will get pretty expensive. Might be better to process the file line by line and ask the question if you really need a regular expression if the structure is like you described in your example. And why to remove unwanted data instead of just extracting the one you want?

Some example:

$fp = fopen('someFile.txt', 'r') or die('unable to open file');
while (($line = fgets($fp)) !== false) {
    if (strpos($line, '(') === false) {
        continue;
    }
    $email = rtrim(mb_substr($line, 0, mb_strpos($line, '(')));
    printf('found: %s'.PHP_EOL, $email);
}
fclose($fp);

In this example, we process the file line by line and only extract the email address by assuming the email address will be before the first opening parentheses in each line - skipping any lines that have no opening parentheses.

Answer 2

You will have to start with reading in the file, before you can process it. In this case it will probably be more useful to read in the lines separately using file().

After that we will do what you probaby already did (but you did not post any code), and use preg_replace().

<?php
$data=file("data.txt",FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES);
foreach($data as $key=>$line){
    $data[$key]=preg_replace('/ \(deleted\)[0-9]+$/m',$line,'');
}
?>

Now $data will contain the lines with the "interesting" information.

READ ALSO
finding/calculating closest objects on cartesian plane by distance PHP

finding/calculating closest objects on cartesian plane by distance PHP

So I'm trying to create a script in PHP that has multiple objects on a cartesian plane (xy) and to find the closest distance

34
Contact Form PHP - send from specific email [duplicate]

Contact Form PHP - send from specific email [duplicate]

This question already has an answer here:

70
PHP contact form is not sending email. [duplicate]

PHP contact form is not sending email. [duplicate]

This question already has an answer here:

81
Laravel - files mimetype validation failing for some files with the same mime

Laravel - files mimetype validation failing for some files with the same mime

I've got two mp3 files, let's say file1mp3 and file2

101