获取两个字符串之间的内容 PHP [英] Get content between two strings PHP
本文介绍了获取两个字符串之间的内容 PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
获取两个字符串之间的内容的最佳方法是什么,例如
Whats is the best way to obtain the content between two strings e.g.
ob_start();
include('externalfile.html'); ## see below
$out = ob_get_contents();
ob_end_clean();
preg_match('/{FINDME}(.|
*)+{/FINDME}/',$out,$matches);
$match = $matches[0];
echo $match;
## I have used .|
* as it needs to check for new lines. Is this correct?
## externalfile.html
{FINDME}
Text Here
{/FINDME}
出于某种原因,这似乎在我的代码中的一个地方起作用,而在另一个地方不起作用.我是否以正确的方式解决这个问题?或者有更好的方法吗?
For some reason this appears to work on one place in my code and not another. Am I going about this in the right way? Or is there a better way?
输出缓冲区也是这样做的方式还是file_get_contents?
Also is output buffer the way to do this or file_get_contents?
提前致谢!
推荐答案
- 使用
#
而不是/
这样您就不必转义它们. - 修饰符
s
使.
和s
也包括换行符. {
和}
具有各种功能,例如{n,m}
中从 n 到 m 次.基础
- Use
#
instead of/
so you dont have to escape them. - The modifier
s
makes.
ands
also include newlines. {
and}
has various functionality like from n to m times in{n,m}
.The basic
preg_match('#\{FINDME\}(.+)\{/FINDME\}#s',$out,$matches);
各种标签等的高级功能(javascript 的样式不太好).
The advanced for various tags etc (styling is not so nice by the javascript).
$delimiter = '#'; $startTag = '{FINDME}'; $endTag = '{/FINDME}'; $regex = $delimiter . preg_quote($startTag, $delimiter) . '(.*?)' . preg_quote($endTag, $delimiter) . $delimiter . 's'; preg_match($regex,$out,$matches);
- 对于您不想执行任何stray php 代码的任何文件,您应该使用file_get_contents.include/require 甚至不应该是那里的一个选项.
- For any file which you do not want to execue any stray php code, you should use file_get_contents. include/require should not even be an option there.
将此代码放入函数中
这篇关于获取两个字符串之间的内容 PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- Use
查看全文