简体   繁体   中英

Splitting strings with regular expression in PHP

Can someone please tell me why the result that I get is different from the book?

Here is the code

<?php
$address = "username@example.com";
$arr = split ("\.|@", $address);
while (list($key, $value) = each($arr))
{
    echo "<br/>".$value;
}
?>

Here is the result the book says you should get

username
@
example
.
com

Here is what I got when I try the code on my computer

Deprecated: Function split() is deprecated in C:\Apache24\htdocs\test3.php on line 3

username
example
com

The split() function has been deprecated since PHP 5.3.0.

Use preg_split() instead.

The usage of this is the same as split() .

The book is wrong in that you should not get the delimiter characters themselves, only the 'words' between them.

The warning is due to split() about to being discontinued in favor of preg_split() , so you should replace it with

$arr = preg_split ('/\.|@/', $address);

to prevent the warning.

I'd recommend that you split by @ only first, and only then split the domain name by . , otherwise you wouldn't know whether foo.bar@example.com or foo@bar.example.com lead to a

foo
bar
example
com

result.

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