1

I have some string:

It's not big deal

I want to change it to

It's not_big deal

So far, I try this code but return "undefined offset: $y"

function checkNegation($word){
$input      = strtolower($word);
$split      = preg_split('/\s+/', $input);
$length     = count($split);

$neg = "NOT_";
for ($x=0; $x<$length; $x++){
    if (preg_match("/\bNOT\b/i",$split[$x])){
        $y=$x+1;
        $split[$x]      = "{$neg}{$split[$y]}";
        unset($split[$y]);
    }
}
  $word = implode(" ",$split);
  return $word;
}

can you help me? thank you :')

barney
  • 59
  • 1
  • 7

2 Answers2

0

if you're using regex already, why do you need to break the string into array of words? you can just match "not" in it and replace it with "not_". why over-complicate things?

your program seems to be running fine. but it'll cause problem if the word "not" is the last word in the string. because in that case, $y will go out of array range.

Mridul Kashyap
  • 704
  • 1
  • 5
  • 12
0

Why not just preg_replace?

$str = "It's not big deal";

echo preg_replace("/\b(not)\s+/i", "$1_", $str); // It's not_big deal
user94559
  • 59,196
  • 6
  • 103
  • 103