Liz*_*ard 24 php regex output-buffering file-get-contents
什么是获取两个字符串之间内容的最佳方式,例如
ob_start();
include('externalfile.html'); ## see below
$out = ob_get_contents();
ob_end_clean();
preg_match('/{FINDME}(.|\n*)+{\/FINDME}/',$out,$matches);
$match = $matches[0];
echo $match;
## I have used .|\n* as it needs to check for new lines. Is this correct?
## externalfile.html
{FINDME}
Text Here
{/FINDME}
Run Code Online (Sandbox Code Playgroud)
出于某种原因,这似乎适用于我的代码中的一个地方而不是另一个地方.我是否以正确的方式解决这个问题?或者,还有更好的方法?
输出缓冲区也是这样做的方法还是file_get_contents?
提前致谢!
Ada*_*ght 42
您也可以使用substr和strpos.
$startsAt = strpos($out, "{FINDME}") + strlen("{FINDME}");
$endsAt = strpos($out, "{/FINDME}", $startsAt);
$result = substr($out, $startsAt, $endsAt - $startsAt);
Run Code Online (Sandbox Code Playgroud)
您需要添加错误检查以处理它不是FINDME的情况.
OIS*_*OIS 42
#而不是/你不必逃避它们.s使得.与\s包括换行符.{并}具有从n到m倍的各种功能{n,m}.基础的
preg_match('#\\{FINDME\\}(.+)\\{/FINDME\\}#s',$out,$matches);
Run Code Online (Sandbox Code Playgroud)各种标签的高级等(javascript的样式不是很好).
$delimiter = '#';
$startTag = '{FINDME}';
$endTag = '{/FINDME}';
$regex = $delimiter . preg_quote($startTag, $delimiter)
. '(.*?)'
. preg_quote($endTag, $delimiter)
. $delimiter
. 's';
preg_match($regex,$out,$matches);
Run Code Online (Sandbox Code Playgroud)将此代码放在一个函数中
如果可能的话,我喜欢避免使用正则表达式,这里是获取两个字符串之间的所有字符串并返回一个数组的替代解决方案。
function getBetween($content, $start, $end) {
$n = explode($start, $content);
$result = Array();
foreach ($n as $val) {
$pos = strpos($val, $end);
if ($pos !== false) {
$result[] = substr($val, 0, $pos);
}
}
return $result;
}
print_r(getBetween("The quick brown {{fox}} jumps over the lazy {{dog}}", "{{", "}}"));
Run Code Online (Sandbox Code Playgroud)
结果 :
Array
(
[0] => fox
[1] => dog
)
Run Code Online (Sandbox Code Playgroud)
我喜欢这两个解决方案
function GetBetween($content,$start,$end)
{
$r = explode($start, $content);
if (isset($r[1])){
$r = explode($end, $r[1]);
return $r[0];
}
return '';
}
function get_string_between($string, $start, $end){
$string = " ".$string;
$ini = strpos($string,$start);
if ($ini == 0) return "";
$ini += strlen($start);
$len = strpos($string,$end,$ini) - $ini;
return substr($string,$ini,$len);
}
Run Code Online (Sandbox Code Playgroud)
我还对上述两种解决方案进行了一些基准测试,并且两者几乎同时给出。你也可以测试一下。我给了两个函数一个文件来读取它有大约 60000 个字符(用 Word 女士的字数检查),两个函数导致大约 0.000999 秒找到。
$startTime = microtime(true);
GetBetween($str, '<start>', '<end>');
echo "Explodin Function took: ".(microtime(true) - $startTime) . " to finish<br />";
$startTime = microtime(true);
get_string_between($str, '<start>', '<end>');
echo "Subsring Function took: ".(microtime(true) - $startTime) . " to finish<br />";
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
61306 次 |
| 最近记录: |