简体   繁体   English

在PHP中使用正则表达式分割字符串

[英]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. 自PHP 5.3.0起不推荐使用split()函数。

Use preg_split() instead. 请改用preg_split()

The usage of this is the same as split() . 其用法与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 该警告是由于split()即将终止而改用preg_split() ,因此您应该将其替换为

$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还是foo@bar.example.com导致

foo
bar
example
com

result. 结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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