display the result of a foreach outside the loop

Asked

Viewed 88 times

-1

Hello,

I need to present the result of a foreach out of the loop. The way I have been doing only presents one result. What I’m doing wrong?

  //Check bad words


$badWords = array('palavra1', 'palavra2', 'palavra3');

$string = "A palavra1 é igual a palavra2 que é diferente da palavra3";
$matches = array();
$matchFound = preg_match_all(
                "/\b(" . implode($badWords,"|") . ")\b/i", 
                $string, 
                $matches
              );

if ($matchFound) {
  $words = array_unique($matches[0]);
  foreach($words as $word) {
    $p[i] = $word;
    $i++;
  }
  echo '<div class="notice notice-danger">A historia contém palavras censuradas, não poderá ser publicada. (';
  print_r($p[i]);
  echo ' ) </div>';

  die();
}

1 answer

3


You have a bit of a mistake in $p[i] whereas i does not exist (nor $p at that point, but in php an array can be declared when it is first populated).

Taking advantage of the code with but due fixes:

$badWords = array('palavra1', 'palavra2', 'palavra3');

$string = "A palavra1 é igual a palavra2 que é diferente da palavra3";
$matchFound = preg_match_all(
                "/\b(" . implode($badWords,"|") . ")\b/i", 
                $string, 
                $matches
              );

$p = array();
if ($matchFound > 0) {
  $words = array_unique($matches[0]);
  foreach($words as $word) {
    $p[] = $word;
  }
  echo '<div class="notice notice-danger">A historia contém palavras censuradas, não poderá ser publicada. (';
  print_r($p);
  echo ' ) </div>';

  die();
}

DEMONSTRATION

You have better and no regex ways of achieving this:

$badWords = array('palavra1', 'safgfsa', 'palavra2', 'palavra3', 'pal4');

$string = "A palavra1 é igual a palavra2 que é diferente da palavra3";

$p = array();
foreach(explode(' ', $string) as $v) {
    $v = str_replace([',', '.', ';', '?', '!', ':'], ['', '', '', '', '', ''], $v); // eliminar entropia, retirar pontuacao de acordo com a nossa lingua
    if(in_array($v, $badWords)) {
        $p[] = $v;
    }
}

$p = array_unique($p);
if(count($p) > 0) {
    echo "foram encontradas palavras<br>";
    echo implode(', ', $p); // imprimir palavras encontradas separadas por virgula e espaco
}

DEMONSTRATION

OUTPUT:

foram encontradas palavras
Array
(
    [0] => palavra1
    [1] => palavra2
    [2] => palavra3
)
  • And how do I remove the word "Array" from the result? Now the result is:(Array ( [0] => word1 [1] => word2 [2] => word3 ) and I wanted it to be just (word1, word2, word3)

  • 1

    I got echo implode( ', ', $p );

  • 1

    @Brunoserrano, I didn’t think that was the problem, I thought it was about the mistake that was making

Browser other questions tagged

You are not signed in. Login or sign up in order to post.