Search code examples
phpmultidimensional-arraystr-replace

Is there a possible way to use multidimensional arrays to replace words in a string using str_replace() and the array() function?


Note: I have seen this question here, but my array is completely different.

Hello everyone. I have been trying to make a censoring program for my website. What I ended up with was:

$wordsList = [
    array("frog","sock"),
    array("Nock","crock"),
];

$message = str_replace($wordsList[0], $wordsList[1], "frog frog Nock Nock");
echo $message;

What I am trying to do is replace "frog" with "sock" using multidimentional arrays without typing all of the words out in str_replace();

Expected Output: "sock sock crocs crocs"

However, when I execute it, for some unknown reason it doesn't actually replace the words, without any errors. I think it's a rookie mistake that I made, but I have searched and have not found any documentation on using a system like this. Please help!


Solution

  • You need to change the structure of your wordsList array.

    There are two structures that will make it easy:

    As key/value pairs

    This would be my recommendation since it's super clear what the strings and their replacements are.

    // Store them as key/value pairs with the search and replacement strings
    $wordsList = [
        'frog' => 'sock',
        'Nock' => 'crock',
    ];
    
    $message = str_replace(
        array_keys($wordsList), // Get all keys as the search array
        $wordsList,             // The replacements
        "frog frog Nock Nock"
    );
    

    Demo: https://3v4l.org/WsUdn

    As a multidimensional array

    This one requires you to add the search/replacement values in the same order, which can be hard to read when you have a few different strings.

    $wordsList = [
        ['frog', 'Nock'],  // All search strings
        ['sock', 'crock'], // All replacements
    ];
    
    $message = str_replace(
        $wordsList[0], // All search strings
        $wordsList[1], // The replacements strings
        "frog frog Nock Nock"
    );
    

    Demo: https://3v4l.org/RQjC6

    If you can't change the original array, then create a new array with the correct structure since that won't work "as is".