在某个字符位置之前的字符串中搜索值。 [PHP] [英] Search for value in string before a certain character position. [PHP]
本文介绍了在某个字符位置之前的字符串中搜索值。 [PHP]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在建立一个显示备份信息的网站。
I am making a website that displays backup information.
我遇到的障碍是,我需要在某个角色位置之前获取信息。
The obstacle that I'm getting is that I need to get info before a certain character position.
字符串看起来像:
Data1 => 2019-06-30-08-00-00,2019-07 -30-08-00-00,2019-08-30-08-00-00 Data2 => 2019-06-30-08-30-00,2019-07-30-08-30-00,2019-08 -30-08-30-00
Data1 => 2019-06-30-08-00-00 , 2019-07-30-08-00-00 , 2019-08-30-08-00-00 Data2 => 2019-06-30-08-30-00 , 2019-07-30-08-30-00 , 2019-08-30-08-30-00
我的代码用于从字符串中获取所有搜索信息。
My code for getting all search info from string.
$BackupJob_list = $BackupJob_list['Data'];
$BackupJob_list = json_encode($BackupJob_list);
$string = "$BackupJob_list"; //String where I need the info from
$needle = "2019-08-30"; //The search value
$lastPos = 0; //Starting position
$positions = array();
//Get lastPos and go again...
while (($lastPos = strpos($string, $needle, $lastPos))!== false) {
$positions[] = $lastPos;
$lastPos = $lastPos + strlen($needle);
}
//Echo every value that is found in the string.
foreach ($positions as $value) {
echo substr($BackupJob_list, $value, 19)."<br/>";
}
我想要得到的是:
2019-06-30-08-00-00
现在我要得到
2019-06-30-08-00-00
2019-06-30-08-30-00
推荐答案
您可以使用 strpos
(文档)进行以下检查:
You can use strpos
(doc) to check that as:
$str = "2019-06-30-08-00-00,2019-07-30-08-00-00,2019-08-30-08-00-00";
$needle = "2019-08-30";
$arr = explode(",", $str); // convert string to array
foreach($arr as $e) {
if (strpos($e, $needle) === 0) echo "Found! Here: $e \n";
}
这篇关于在某个字符位置之前的字符串中搜索值。 [PHP]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文