I have an array $track['context']
This outputs the following
常州, 的, 妈咪ZA, 已揽件快件已从, 常州, 发出快件到达
Each one of these are tracking details.
I am running the array through the following code to try and run a preg_match
for each item that is inside of $track['context']
then replace if a string from $badWords
is present
$badWords = ['常州', '的']; // I would want these to end up being ['one', 'two']
$arrayToCheck = $track['context'];
foreach ($badWords as $badWord) {
if (preg_match("/($badWord)/", $arrayToCheck)) {
// Do I run my preg_match function here?
}
}
I would suggest a data structure for the bad words, where the word is the key and the replacement the value in an associative array.
Then you could loop over your content array, and do the replacement with a callback function:
// Sample data:
$track['context'] = array(
'qdf 常州',
'fdhlkjfq fdkq ',
'的 fdsqfsf'
);
// Make a translation table for the bad words:
$badWords = [
'常州' => 'one',
'的' => 'two'
];
// Build a regular expression that matches any of the above words:
$regexp = "/\b(" . implode('|', array_map('preg_quote', array_keys($badWords))) . ")\b/u";
// Iterate over the content
foreach ($track['context'] as &$subject) {
$subject = preg_replace_callback($regexp, function($matches) use ($badWords) {
// Replace the matched bad word with what we have mapped for it:
return $badWords[$matches[0]];
}, $subject);
}
// Output results:
print_r ($track['context']);
See it run on eval.in