preg_grep 处理较大的字符串

发布于 2024-08-12 18:42:11 字数 770 浏览 3 评论 0原文

我需要在某个包含 html 文件内容的字符串上使用 preg_reg 。

$file = file_get_contents($path);
$html_array = explode(' ', $file);

问题是数组有时看起来像这样:

[77]=>
    string(35) "<div>
</div>
<br>
{{testto}}
<br>"

我尝试在那里放入一些空格.. :P 不起作用.. :/ 稍后我将像这样执行 preg_grep :

$childframes = preg_grep('!\{\{(\w+)\}\}!', $html_array);
$retur = array();
foreach($childframes as $v){
   $v = trim($v);
   $retur[] = substr($v, 2, -2);
}
return $retur;

所以这个想法基本上是得到 < code>{{testto}} 在数组中,每次出现 {{sometext}} 时,我都会将其子串为仅“sometext”。

谢谢=)

编辑:

重复这个问题:爆炸无法正常工作,所以如果可能的话我需要一些正则表达式,而不仅仅是空格......,并且有没有更好的方法在大型上执行 preg_grep细绳?

I need to use preg_reg on some string with content from a html file.

$file = file_get_contents($path);
$html_array = explode(' ', $file);

The problem is that the array looks sometimes like this:

[77]=>
    string(35) "<div>
</div>
<br>
{{testto}}
<br>"

I have tried to put in some whitespaces there.. :P Won't work.. :/ Later on I will do a preg_grep like this:

$childframes = preg_grep('!\{\{(\w+)\}\}!', $html_array);
$retur = array();
foreach($childframes as $v){
   $v = trim($v);
   $retur[] = substr($v, 2, -2);
}
return $retur;

So the idea is basically to get {{testto}} in a array, every occurrence of {{sometext}} where I substring it down to only 'sometext'.

Thanks =)

EDIT:

To repeat the problem: explode is not working right so I need some regex if possible, instead of just whitespace.., and is there any better way to do preg_grep on on a large string?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

不需要爆炸,创建一个临时数组,grep它并稍后剥离它,只需一个正则表达式匹配:

$html = file_get_contents($path);
preg_match_all('#{{(.*?)}}#', $html, $matches);
$array_of_texts = $matches[1];

No need to explode, create a temporary array, grep it and strip it later, just a regexp match:

$html = file_get_contents($path);
preg_match_all('#{{(.*?)}}#', $html, $matches);
$array_of_texts = $matches[1];
猫七 2024-08-19 18:42:11

难道您只想使用:

strip_tags($v)

首先删除所有 html 标签,然后您的代码将正确获取“sometext”。

Don't you just want to use:

strip_tags($v)

first so that you are removing all of the html tags, then your code will get the 'sometext' correctly.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文