I have the following code where I am trying to match specific words exactly using word boundaries, replace them with "censored" and then rebuild the text but for some reason the regex is catching a trailing slash. I've simplified down to the following test case for clarity
<?php
$words = array('bad' => "censored");
$text = "bad bading testbadtest badder";
$newtext = "";
foreach( preg_split( "/(\[\/?(?:acronym|background|\*)(?:=.+?)?\]|(^|\W)bad(\W|$))/i", $text, null, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY ) as $section )
{
if ( isset( $words[ $section ] ) )
{
$newtext .= $words[ $section ];
}
else
{
$newtext .= $section ;
}
}
var_dump($newtext);
exit;
In this example I am expecting to match on "bad" but not bading testbadtest or badder. The issue is "bad " (note the trailing space) is being matched which does not exist as a key in the $words array.
Could somebody please explain where I may be going wrong?
Thanks in advance