简体   繁体   中英

How to check in PHP8 if a unknown variable (e.g. e-mail) is in a string?

I usually checked this with the following code:

$email = '/[^@:="\'\s]*@[^@\s]*\.[a-z]+/iU';
if(preg_match($email,$article->text) == true) {
to something
}

In PHP 8 this is deprecated (Works, but with warning), because I can't always guarantee that there really is an email in it.

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

What are the alternatives?

I know that this solution still works, but I want to be fit for the future.

When searching, I did not find a solution. "str_contains" seems to allow only one string.

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

First of all, this warning only appears if you enable strict typing (which is a good thing, don't get me wrong):

declare(strict_types=1);

It makes more sense to avoid the check altogether:

if ($article->text !== null && preg_match($email, $article->text)) {
}

But, if that isn't feasible for whatever the reason, you can also default to empty string:

if (preg_match($email, $article->text ?? '')) {
}

On a side note, PHP has native email validation .

It is actually not caused by PHP, but by the Joomla CMS. There are situations where $article->text has not been defined. Thanks to all who have steered mine in the right direction through their thoughts.

$email = '/[^@:="\'\s]*@[^@\s]*\.[a-z]+/iU';
if($article->text AND preg_match($email,$article->text) == true) {
  to something
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM