Zend certified PHP/Magento developer

TypeError: str_replace(): Argument must be of type array|string, null given

I am getting the below error:

main.CRITICAL: TypeError: str_replace(): Argument #3 ($subject) must be of type array|string, null given

In the following code:

public function beforeSendResponse(Http $subject)
    {
        if ($this->ampService->isAmp()) {
            return;
        }

        $store = $this->storeManager->getStore();

        if (!$this->configProvider->getGeneralIsEnable($store) && !$this->configProvider->getIsPixelEnabled($store)) {
            return;
        }

        $content = $subject->getContent();

        if ($this->configProvider->getGeneralIsEnable($store)) {
            $regularCode = $this->configProvider->getGeneralRegularCode($store);

            $subject->setContent(
                str_replace('</head>', $regularCode . "n</head>", $content)
            );
        }

        if ($this->configProvider->getIsPixelEnabled($store)) {
            $regularCode = $this->configProvider->getPixelCode($store);

            $subject->setContent(
                str_replace('</head>', $regularCode . "n</head>", $content)
            );
        }

        if (!empty($this->configProvider->getPixelDomainVerification($store))) {
            $regularCode = $this->configProvider->getPixelDomainVerification($store);

            $subject->setContent(
                str_replace('</head>', $regularCode . "n</head>", $content)
            );
        }
    }
}

No written by me. It seems that with php8.1 line:

str_replace('</head>', $regularCode . "n</head>", $content)

throw error:

 main.CRITICAL: TypeError: str_replace(): Argument #3 ($subject) must be of type array|string, null given

As I inspect this code tries to put javascript code to the footer before send a request. It is uses in a custom module for GTM

Now sure how to fix it.

Any help please?