如何提取字符串的一部分
how to extract parts of the string
我在 PHP 中有以下字符串。
"File:content/resources/11933/Calm_Nebula_by_The_Free_Mason.jpgDate:Fri Mar 18 11:30:17 CET 2016Size:23124"
我需要分别获取文件、日期和大小。
提取所需值的最佳方法是什么?
explode() OR substring()
分解需要一些公共值,子字符串需要开始和结束。在这两种情况下,我都有点困惑。
如有任何帮助,我们将不胜感激。
试试这个:
<?php
$text = "File:content/resources/11933/Calm_Nebula_by_The_Free_Mason.jpgDate:Fri Mar 18 11:30:17 CET 2016Size:23124";
$pattern = '/file:(.*?)date:(.*?)size:(.*)/i';
preg_match($pattern, $text, $out);
print_r($out);
?>
输出:
Array
(
[0] => File:content/resources/11933/Calm_Nebula_by_The_Free_Mason.jpgDate:Fri Mar 18 11:30:17 CET 2016Size:23124
[1] => content/resources/11933/Calm_Nebula_by_The_Free_Mason.jpg
[2] => Fri Mar 18 11:30:17 CET 2016
[3] => 23124
)
我在 PHP 中有以下字符串。
"File:content/resources/11933/Calm_Nebula_by_The_Free_Mason.jpgDate:Fri Mar 18 11:30:17 CET 2016Size:23124"
我需要分别获取文件、日期和大小。
提取所需值的最佳方法是什么?
explode() OR substring()
分解需要一些公共值,子字符串需要开始和结束。在这两种情况下,我都有点困惑。
如有任何帮助,我们将不胜感激。
试试这个:
<?php
$text = "File:content/resources/11933/Calm_Nebula_by_The_Free_Mason.jpgDate:Fri Mar 18 11:30:17 CET 2016Size:23124";
$pattern = '/file:(.*?)date:(.*?)size:(.*)/i';
preg_match($pattern, $text, $out);
print_r($out);
?>
输出:
Array
(
[0] => File:content/resources/11933/Calm_Nebula_by_The_Free_Mason.jpgDate:Fri Mar 18 11:30:17 CET 2016Size:23124
[1] => content/resources/11933/Calm_Nebula_by_The_Free_Mason.jpg
[2] => Fri Mar 18 11:30:17 CET 2016
[3] => 23124
)