标签:php
我有一个包含以下内容的文件.我想搜索字符串“ 13030115 …”,即“#”之前的值.但是搜索应向后进行,即从下至上.如何在PHP中做到这一点?
1303011581#user: textMsg
1303011582#user: textMsg
1303011583#user: textMsg
1303011584#user: textMsg
1303011585#user: textMsg
1303011586#user: textMsg
解决方法:
$messages = "1303011581#user: textMsg
1303011582#user: textMsg
1303011583#user: textMsg
1303011584#user: textMsg
1303011585#user: textMsg
1303011586#user: textMsg";
$messages = explode("\n", $messages);
$c_messages = count($messages);
for ($i = 0; $i < $c_messages; $i++) {
$index = ($c_messages-$i)-1;
if ($messages[$index] != '') {
$message = explode("#", $messages[$index]);
$id = $message[0];
$text = substr($messages[1], strpos($messages[1],':')+2);
echo "$id: $text\r";
}
}
?>
编辑
重读您的问题后,这是另一种应该更快的方法:
$messages = "1303011581#user: textMsg1
1303011582#user: textMsg2
1303011583#user: textMsg3
1303011584#user: textMsg4
1303011585#user: textMsg5
1303011586#user: textMsg6";
function findMessage($id, $messages) {
if (strpos($messages, $id) === false) {
return false;
}
$message = substr($messages, strpos($messages, $id));
$message = substr($message, strpos($message, ':')+2);
$message = substr($message, 0, strpos($message, "\n"));
return $message;
}
echo findMessage('1303011582', $messages);
?>
标签:php
来源: https://codeday.me/bug/20191208/2092001.html