Preg_match null in php 8.3

I am passing null to the subject in preg_match but in php 8.3 I am throwing errors with this. I need to know how to get rid of the error in php 8.3.

ERROR

Deprecated: preg_match(): Passing null to parameter #2 ($subject) of type string is deprecated in /homepages/22/d4299051200/htdocs/admin/include/xtemplate.class.php on line 603

CODE

preg_match('/^\n/', $var) && preg_match('/\n$/', $var):

The error is telling you that $var is null.
So the fix is… to make it not null.

In XTemplate sometimes it passes it a nulland sometimes it doesnt. I think anyways. Is there a way to let it pass a null. Although it still works passing the null just throws an error.

The function does not allow null.
So your choices are… make it not null, or dont use the function.

Just add a

?? “”

Behind the $var

So I just add two question marks. I’ll try that.

I noticed that this is going on in the code. I was wondering how to change this from a null to empty.

$var = isset($this->parsed_blocks[$bname2]) ? $this->parsed_blocks[$bname2] : null;

by… replacing the word ‘null’ with the empty string ("")?

I tried to use the question marksand this is what I get. The way might be to do empty not null.

case preg_match('/^\n/', $var??) && preg_match('/\n$/', $var??):


Parse error: syntax error, unexpected token ")" in /homepages/22/d4299051200/htdocs/admin/include/xtemplate.class.php on line 603

Not quite. If you read the post from @Thallius above, you’ll see that you’re missing the pair of double-quotes after the pair of question marks.

The double-question-mark is a shortened way of saying “if the first parameter is null or does not exist, replace it with this string, otherwise return the original parameter”, and you’ve omitted “this string” from your code. Look up “Null Coalescing Operator” for more information.

1 Like

To be fair/pedantic, the Null Coalescing Operator can be used for anything, not just strings.
X ?? Y means “if X is null, then Y, else X.”

It’s (almost) equivalent to the line of code you gave above:

(This is “if X is not null, then X, else Y”, but the theory’s the same. the NCO just does it in shorthand.)

1 Like

In PHP 8.3, you must ensure $var is a string before using preg_match. Use:
is_string($var) && preg_match(‘/^\n/’, $var) && preg_match(‘/\n$/’, $var);
This prevents the warning when $var is null.