【问题标题】:preg_grep with html sourcepreg_grep 与 html 源
【发布时间】:2024-01-07 15:15:02
【问题描述】:

我要提取这一行

<p>@include{"portal.shared.blook"}</p>

使用

preg_grep("/(\s*@include.*)/",explode("\n", $Source)) 

来自这个源代码

<html>
   <head>
        <title>hi</title>
   </head>
   <body>
        <h1>Hi I am layout</h1>
        <br>
        <p>@include{"portal.shared.blook"}</p>
        @require{"portal.shared.footer":"[main]"}

有时代码有空格,我无法处理

【问题讨论】:

  • 这条线会一直这样吗? &lt;p&gt;@include{"Some Text here"}&lt;/p&gt;
  • 是的,但是“这里有一些文字”更改
  • 空格可以用字符\s来表示
  • 我到达了这个 preg_grep('/(@include{"(.*)"}*)/',explode("\n", $Source) 但仍然显示

    标签

  • 之后你可以这样做:preg_replace('/&lt;p&gt;/', '', preg_replace('/&lt;/p&gt;/', '', $string));

标签: php expression preg-grep


【解决方案1】:

试试这个:

(?<=\<\w\>)(\s*@include.*)(?=\<\/\w\>)

工作示例: https://regex101.com/r/wM1lB8/2

【讨论】:

  • 我到达这个 "(@include{"(.*)"}*)" 它在在线测试仪上没问题,但在 php 本地仍然有

    附加

  • 你是如何在 PHP 代码中使用它的?可以发一下吗?
  • 当然,$Source 是 html 文件 foreach(preg_match('/(@include{"(.*)"}*)/', $Source) as $Tempstring) { print_r( $Tempstring) ; }
  • preg_match 返回一个整数。你不应该使用这种方式。你可以这样做:preg_match('/(?&lt;=\&lt;\w\&gt;)(\s*@include.*)(?=\&lt;\/\w\&gt;)/', $Source, $matches); 然后遍历$matches