以下PHP代码将多行字符串分解为数组。然后,使用三个if
语句检查数组中是否存在特定行,并在存在任何特定行的情况下回显相应的文本。
$multiline_string = 'First line
Second line
Third line';
$array = explode("\n", $multiline_string);
if (in_array('First line', $array))
{
echo 'First line exists.';
}
if (in_array('Second line', $array))
{
echo 'Second line exists.';
}
if (in_array('Third line', $array))
{
echo 'Third line exists.';
}
问题在于仅回显Third line exists.
,这意味着在数组中找不到第一行和第二行。
但是我使用print_r($array)
进行了调试,并得到了以下输出:
Array
(
[0] => First line
[1] => Second line
[2] => Third line
)
因此第一行和第二行确实存在于数组中。 in_array
函数为什么找不到它们?
答案 0 :(得分:1)
要了解发生了什么,您需要了解关于在文本文件中如何表示行尾有多种约定。
\n
分隔行。\r\n
。\r
分隔行。您可能不必担心这一点,因为在实践中很少遇到这种情况。维基百科上有a good summary that explains the history of these different standards。
您的示例文件似乎是在Windows上创建的,因此每行之间有两个字符。这意味着当您在explode()
上\n
时,除最后一行外,每一行的末尾都将包含一个不可见的\r
字符。这就是为什么示例中只有最后一行匹配的原因。
有多种解决方案,具体取决于多行字符串数据的来源。
如果您的情况如示例所示,该字符串在您控制的文件中定义为文字字符串,则有两种选择:
$array = explode("\r\n", $multiline_string);
,以便基于Windows行尾进行爆炸。另一方面,如果您的数据来自用户输入,则应对其进行编码以处理两种类型的行尾 1 。这里也有几个选项:
explode()
调用替换为$array = preg_split("/\r?\n/", $multiline_string)
,这将在\n
或\r\n
的任何实例上爆炸。explode()
。例如,$multiline_string = str_replace("\r\n", "\n", $multiline_string);
。如果稍后要对字符串进行其他操作,例如将其存储在数据库中,因为这意味着您只需要处理一次即可,而不必在所有情况下都应对两种可能性。1 或全部三种类型,如果您想更全面的话。留给读者练习……
答案 1 :(得分:0)
改为尝试preg_split
。它允许您使用正则表达式而不是完全匹配的字符串。
$multiline_string = 'First line
Second line
Third line';
$array = preg_split("/\r?\n/", $multiline_string);
if (in_array('First line', $array))
{
echo 'First line exists.';
}
if (in_array('Second line', $array))
{
echo 'Second line exists.';
}
if (in_array('Third line', $array))
{
echo 'Third line exists.';
}
答案 2 :(得分:0)
如果使用双引号而不是单引号并添加回车符\ r,它将打印出三行(注意,我们不将\ r放在第三行)
<?php
$multiline_string = 'First line
Second line
Third line';
$array = explode("\n", $multiline_string);
dd($array);
if (in_array("First line\r", $array)){ //here we added a carriage return
echo 'First line exists.'.'<br>';
}
if (in_array("Second line\r", $array)){ //here we added a carriage return
echo 'Second line exists.'.'<br>';
}
if (in_array("Third line", $array)){ //here we did not
echo 'Third line exists.'.'<br>';
}
function dd($something){
echo '<pre>';
var_dump($something);
echo '</pre>';
}
,输出将是:
array(3) {
[0]=>
string(11) "First line
"
[1]=>
string(12) "Second line
"
[2]=>
string(10) "Third line"
}
First line exists.
Second line exists.
Third line exists.