Sil hat PHP ile belirli bir kelime / cümle içeriyor

5 Cevap php

beyler ben bir metin dosyası var ve ben belirli sözcükleri içeren bazı satırları kaldırmak istiyorum

 <?php
// set source file name and path
$source = "problem.txt";

// read raw text as array
$raw = file($source) or die("Cannot read file");

şimdi ben bazı satırları kaldırmak istiyorum ve bu yüzden onları kullanmak istediğiniz dizisi var.

5 Cevap

Eğer bir dizinin bir satır dosyanızın her çizgi var gibi, array_filter function might interest you (quoting):

array array_filter  ( array $input  [, callback $callback  ] )

Iterates over each value in the input array passing them to the callback function.
If the callback function returns true, the current value from input is returned into the result array. Array keys are preserved.

Ve bir dize başka bir yer olup olmadığını belirlemek için strpos or stripos kullanabilirsiniz.


For instance, let's suppose we have this array :

$arr = array(
  'this is a test',
  'glop test',
  'i like php',
  'a badword, glop is', 
);

Biz, "glop" içeren satırları süzmek verecek bir geri çağırma işlevi tanımlayabilirsiniz:

function keep_no_glop($line) {
  if (strpos($line, 'glop') !== false) {
    return false;
  }
  return true;
}

Ve ile bu işlevi kullanın array_filter:

$arr_filtered = array_filter($arr, 'keep_no_glop');
var_dump($arr_filtered);

Ve biz çıktı bu tür almak istiyorum:

array
  0 => string 'this is a test' (length=14)
  2 => string 'i like php' (length=10)

Yani biz "BADWORD" "glop" içeren tüm satırları kaldırdık.


Of course, now that you have the basic idea, nothing prevents you from using a more complex callback function ;-)


Edit after comments : burada çalışmak gerekir kod tam bir bölümü:

Her şeyden önce, hatları listenizi var:

$arr = array(
  'this is a test',
  'glop test',
  'i like php',
  'a badword, glop is', 
);

Then, you load the list of bad words from a file :
And you trim each line, and remove empty lines, to make sure you only end up with "words" in the $bad_words array, and not blank stuff that would cause troubles.

$bad_words = array_filter(array_map('trim', file('your_file_with_bad_words.txt')));
var_dump($bad_words);

$bad_words dizisi benim test dosyası içerir:

array
  0 => string 'glop' (length=4)
  1 => string 'test' (length=4)

Then, the callback function, that loops over that array of bad words :
Note : using a global variable is not that nice :-( But the callback function called by array_filter doesn't get any other parameter, and I didn't want to load the file each time the callback function is called.

function keep_no_glop($line) {
  global $bad_words;
  foreach ($bad_words as $bad_word) {
      if (strpos($line, $bad_word) !== false) {
        return false;
      }
  }
  return true;
}

Ve, daha önce olduğu gibi, sen array_filter satırları filtrelemek için kullanabilirsiniz:

$arr_filtered = array_filter($arr, 'keep_no_glop');
var_dump($arr_filtered);

Hangi, bu kez, size verir:

array
  2 => string 'i like php' (length=10)

Umarım bu yardımcı olur.

Bu, tüm rows bunun bir kara listeye kelime var kaldıracaktır:

$rows = file("problem.txt");    
$blacklist = "foo|bar|lol";

foreach($rows as $key => $row) {
    if(preg_match("/($blacklist)/", $row)) {
        unset($rows[$key]);
    }
}

file_put_contents("solved.txt", implode("\n", $rows));

PHP 5.3 kullanıyorsanız Veya, array_filter ile bir lambda işlevini kullanabilirsiniz:

$rows = file("problem.txt");    
$blacklist = "foo|bar|lol";
$rows = array_filter($rows, function($row) {
    return preg_match("/($blacklist)/", $row);
});

file_put_contents("solved.txt", implode("\n", $rows));

Önce PHP 5.3 kullanarak bir çözüm array_filter aslında ben haberi ilk çözüm daha fazla satır kadar kullanmak istiyorum, bu yüzden dışarı bırakacağım.

strpos fonksiyonu kontrol edin. Bir dizenin başka bir dize ya da değil (ve nerede tam olarak birinci dize ikinci olan) içeriyorsa size söyleyebilir. Bu gibi kullanabilirsiniz:

$good = array();
$bad_words = array('martin', 'methew');

// for every line in the file
foreach($raw as $line) {
  // check for each word we want to avoid
  foreach($bad_words as $word) {
    // if this line has a trigger word
    if(strpos($line, $word) !== false) {
      // skip it and start processing the next
      continue 2;
    }
  }

  // no triggers hit, line is clean
  $good[] = $line;
}

Şimdi $good sadece temiz çizgiler bir liste olurdu.

Eğer "kötü sözler" bir dizi var olduğunu varsayarsak:

<?php
foreach ($raw as $key=>$line)
{
    foreach ($badwords as $w)
    {
        if ( strpos($line, $w) !== false )
            unset($raw[$key]);
    }
}
?>

Eğer uzun bir dize yerine bir dosya varsa ve belirli sözler olduğunu bütün dize satırları kaldırmak istiyorum. Bu kullanabilirsiniz:

$string="I have a long string\n
  That has good words inside.\n
   I love my string.\n
  //add some words here\n";
$rows = explode("\n",$string);
$unwanted = "tring|\/\/";
$cleanArray= preg_grep("/$unwanted/i",$rows,PREG_GREP_INVERT);
$cleanString=implode("\n",$cleanArray);
print_r ( $cleanString );

Bu satırları "tring" ve "/ /" içeren olduğunu kaldırır.