Deprecated: preg_match(): Passing null to parameter #2 ($subject) of type string is deprecated – Php

by
Ali Hasan
composer-php wamp

The Problem:

When using PHP’s preg_match() function, passing a null value as the second parameter (subject string) triggers a deprecation warning. This occurs in a PHP script (config.inc.php), where the preg_match() function is used to extract values from a string ($output) based on a pattern. The specific error message is:

Deprecated: preg_match(): Passing null to parameter #2 ($subject) of type string is deprecated

This problem arises because the $output variable may not always contain a valid string, leading to the null value being passed to preg_match(). To resolve this issue, it’s necessary to ensure that the $output variable always contains a valid string before using it in the preg_match() function.

The Solutions:

Solution 1: Fix the preg_match call

The error message indicates that you are passing a null value to the $subject parameter of the preg_match function. This parameter is expecting a string, so you need to ensure that it contains a valid string.

In your case, you are using the $output variable as the subject, but it appears to be unset. You should instead use the $value variable, which contains the actual string you want to match against.

Solution 2: Fetch current environment encoding and replace array entries with actual values.

The intent of the code fragment appears to be to fetch the current environment encoding and replace the array entries with actual values. To achieve this, you can use the following approach:

$Text_Encoding = array(
    'IsSingleByte' => '',
    'BodyName' => '',
    'EncodingName' => '',
    'HeaderName' => '',
    'WebName' => '',
    'WindowsCodePage' => '',
    'CodePage' => '',
);

$command = 'CMD /D /C powershell [System.Text.Encoding]:: Default';
$output = `$command`;

foreach ($Text_Encoding as $key => $value) {
    if (preg_match('~^'.$key.'\s+:\s+([a-zA-Z0-9-\'() ]+)~mi', $output, $matches) === 1) {
        $Text_Encoding[$key] = $matches[1];
    }
}

Q&A

I am getting Deprecated: preg_match(): Passing null error. How could I fix this problem?

Looks like you need to make this change: from $output to $value.

Is there any other way to fix this Deprecated error.

Here is the fix: $Text_Encoding[$key] = $matches[1];

Video Explanation:

The following video, titled "Unrecognized error number: 8192 || PHPLdapAdmin Error and Fix ...", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

Error: Error Unrecognized error number: 8192: trim(): Passing null to parameter #1 ($string) of type string is deprecated Replacement Folder ...