我需要获取一个包含数据的子字符串,直到字符串后面的第一行中断为止。
我已经尝试过strstr()来查找所需的字符串。但是,它为substr()定义了一个问题,因为我只能将Integer传递给它,而且内容的长度可能不同。
if (strstr($body, 'Post Code:')){
$postcode = substr(strstr($body, 'Post Code:'), 10, $lastChar);
if (strstr($body, 'First name:')){
$firstName = substr(strstr($body, 'First name:'), 11, $lastChar);;
} elseif(strstr($body, 'Last name:')){
$lastName= substr(strstr($body, 'Last name:'), 10, $lastChar);;
} elseif(strstr($body, 'Comments:')){
$comments = substr(strstr($body, 'Comments:'), 9, $lastChar);;
}
$queryFields = "INSERT INTO fields (ID, Postcode, First_name, Last_name, Comments) VALUES ('$id', '$postcode', '$firstName', '$lastName', '$comments')";
$resultFields = mysqli_query($this->connection, $queryFields);
}
答案 0 :(得分:0)
strpos()可以帮助您找到字符串的第一行末尾,因此您可以轻松知道何时处理字符串。
if ($postcode = strstr($body, 'Post Code:')){
$postcode = substr($postcode, 10, strpos($postcode, PHP_EOL)-10);
if ($firstName = strstr($body, 'First name:')){
$firstName = substr($firstName, 11, strpos($firstName, PHP_EOL)-11);
} else {$firstName = '';}
if($lastName = strstr($body, 'Last name:')){
$lastName = substr($lastName, 10, strpos($lastName, PHP_EOL)-10);
} else {$lastName = '';}
if($comments = strstr($body, 'Comments:')){
$comments = substr($comments, 9, strpos($comments, PHP_EOL)-9);
} else {$comments = '';}
$queryFields = mysqli_prepare($this->connection, "INSERT INTO fields (ID, Postcode, First_name, Last_name, Comments) VALUES (?, ?, ?, ?, ?)");
mysqli_stmt_bind_param($queryFields, 'issss', $id, $postcode, $firstName, $lastName, $comments);
$resultFields = mysqli_stmt_execute($queryFields);
}
我自由地改变了我认为有问题的一两件事:
此外,假设您要在某处定义它的值,我也像您一样在查询中保留了$ id。