«é», «è» и все буквы с акцентами НЕ ОТОБРАЖАЮТСЯ в функции PHP с использованием PREG_REPLACE - PullRequest
1 голос
/ 11 июля 2020

Я работаю над поисковой системой. Я нашел в сети хорошо написанную функцию php, позволяющую выводить список ключевых слов из текста. Функция отлично работает на английском sh. Однако, когда я попытался адаптировать его на французском языке, я заметил, что буквы «é», «è», «à» и все буквы с диакритическими знаками не отображаются в выводе массива.

Например, если текст содержит: "Hello Héllo" => => Output = "Hello Hllo"

Думаю, проблема где-то в следующей строке кода:

$text = preg_replace('/[^a-zA-Z0-9 -.]/', '', $text); // only take alphanumerical characters, but keep the spaces and dashes too…

Есть идеи? Большое спасибо из Франции!

Полный код следующий:

function generateKeywordsFromText($text){


// List of words NOT to be included in keywords
  $stopWords = array('à','à demi','à peine','à peu près','absolument','actuellement','ainsi');
  
  $text = preg_replace('/\s\s+/i', '', $text); // replace multiple spaces etc. in the text
  $text = trim($text); // trim any extra spaces at start or end of the text
  $text = preg_replace('/[^a-zA-Z0-9 -.]/', '', $text); // only take alphanumerical characters, but keep the spaces and dashes too…
  $text = strtolower($text); // Make the text lowercase so that output is in lowercase and whole operation is case in sensitive.

  // Find all words
  preg_match_all('/\b.*?\b/i', $text, $allTheWords);
  $allTheWords = $allTheWords[0];
  
  //Now loop through the whole list and remove smaller or empty words
  foreach ( $allTheWords as $key=>$item ) 
  {
      if ( $item == '' || in_array(strtolower($item), $stopWords) || strlen($item) <= 3 ) {
          unset($allTheWords[$key]);
      }
  }   
  
  // Create array that will later have its index as keyword and value as keyword count.
  $wordCountArr = array();
  
  // Now populate this array with keywrds and the occurance count
  if ( is_array($allTheWords) ) {
      foreach ( $allTheWords as $key => $val ) {
          $val = strtolower($val);
          if ( isset($wordCountArr[$val]) ) {
              $wordCountArr[$val]++;
          } else {
              $wordCountArr[$val] = 1;
          }
      }
  }
  
  // Sort array by the number of repetitions
  arsort($wordCountArr);
  
  //Keep first 10 keywords, throw other keywords
  $wordCountArr = array_slice($wordCountArr, 0, 50);
  
  // Now generate comma separated list from the array
  $words="";
  foreach  ($wordCountArr as $key=>$value)
  $words .= " " . $key ;
  
  // Trim list of comma separated keyword list and return the list
  return trim($words," ");
  } 
  echo $contentkeywords = generateKeywordsFromText("Hello, Héllo");

1 Ответ

1 голос
/ 11 июля 2020

Вам необходимо исправить все три звонка preg_replace:

$text = preg_replace('/\s{2,}/ui', '', $text); // replace multiple spaces etc. in the text
$text = preg_replace('/[^\p{L}0-9 .-]+/u', '', $text); // only take alphanumerical characters, but keep the spaces and dashes too…
// Find all words
preg_match_all('/\w+/u', $text, $allTheWords);

См. Демонстрацию PHP

Подробности

  • '/\s{2,}/ui' - это будет соответствовать любым двум или более символам пробелов Unicode
  • '/[^\p{L}0-9 .-]+/u' - соответствует одному или нескольким символам кроме любой буквы Unicode (\p{L}), любого ASCII di git (0-9) или пробел, точка или дефис (обратите внимание, что - должен использоваться в конце класса символов)
  • '/\w+/u' соответствует всем словам Unicode, последовательностям одного или больше букв / цифр / символов подчеркивания.
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...