preg_replace and multidimensional array

Just for reference, is there a way to make the following work…

$x=1;
    
while (mysqli_stmt_fetch($stmt1)){
    $badWordsArray[$x] = array('id' => $badID,
                    'word' => $badWord,
                    'pattern' => "~\b($badWord)(s?)\b~");
    $x=$x+1;
}


$string = 'some bad-ass words here';

$replacements = '****';

$new = preg_replace($badWordsArray[]['pattern'], $replacements, $string);

If I run that code PHP complains…

Fatal error: Cannot use [] for reading in /Users/user1/Documents...

And if I remove the first then PHP complains…

Notice: Undefined index: pattern in /Users/user1/Documents...
Warning: preg_replace(): Empty regular expression in /Users/user1/Documents...

I got things working with a one-dimensional array, but it would be nice to get the above code working so I can use one multidimensional array for several things in my function.

Thanks.

you can transform your badWords array (via array_map() ) so that preg_replace() gets a valid array of patterns.

note: while $badWordsArray[] allows you to define a new array element, for reading an array element you must use an existing key.

I think I understand what array_map does, but I don’t follow what you are suggesting in my particular case…

Again, I’m not following you…

you know what array you have built from your DB query, you know (and if you don’t, read it up in the manual) what array preg_replace() expects. hence, transform array 1 into array 2.

hm, what array element should $badWordsArray[] return to you?

Sorry, but I don’t see how the function or your response helps where I am stuck…

I have a multidimensional array which contains bad words, but it seems that preg_replace only wants $patterns in a one-dimensional array.

I fail to see how array_map would help here.

The first thing I need to know is whether I can coax preg_replace into accepting bad words from my multidimensional array, or if I have to ditch it and create a one-dimesnional array as a compromise.

As it stands, $badWordsArray returns an array of arrays about bad words (i.e. metadata)

example:

$ex = [
    ['foo' => 1, 'bar' => 2], 
    ['foo' => 2, 'bar' => 4], 
    ['foo' => 3, 'bar' => 6], 
];
var_dump(
    array_map(function($item) {
        return $item['foo'];
    }, $ex)
);

that wasn’t the question. it was about what $badWordsArray[] returns, not $badWordsArray

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.