gpt4 book ai didi

php - 通过第一个和最后一个字符将字符串与 php dom xpath 匹配

转载 作者:行者123 更新时间:2023-12-03 16:54:30 25 4
gpt4 key购买 nike

我想通过使用 xpath 搜索文本来匹配以 % 开头并以 % 字符结尾的 html 字符串。

条件:

  • 字符串以 % 开头
  • 字符串以 % 结尾
  • 在一个 html 文档中可以没有或有多个匹配项
  • 字符串可以包含(但是可选的)::但至少需要 1
    ::
  • 前后的字母字符
  • 在第一个和最后一个 % 字母、数字和 - 字符之间
    允许。

  • 我得到的最好的是 $xpath->query("//*[text()[starts-with(., '%')][substring(., string-length(.) - 1) = '%']]");
    但这行不通。 php Dom 的新手,发现自己很难找到答案。解释非常有值(value)!

    提前致谢!

    编辑

    请参阅下面的评论,在这种情况下使用 preg_match_all 更好。目前我为此使用以下代码:
    preg_match_all('/%{1}[a-zA-Z0-9-]+?(::?[a-zA-Z0-9-]+?)?%{1}/', $string, $match);

    接受对此模式的改进。

    最佳答案

    这不是 XPath 的强项——您所描述的最好由 REGEXP 引擎处理(在 PHP 中,这可能意味着迭代节点并通过 preg_match 运行每个节点)。

    尽管如此,这是一种(非常)hacky XPath 方法,我认为它可以满足您的需求。您可以在 this XMLPlayground 看到一个工作演示。

    root/node[
    substring(., 1, 1) = '%' and
    substring(., string-length(.)) = '%' and
    not(string-length(translate(substring(., 2, string-length(.)-2), 'abcdefghijklmnopqrstuvwxyz0123456789-:', ''))) and
    (
    (
    contains(., '::') and
    substring(., 2, 1) != ':' and
    substring(., string-length(.)-2, 1) != ':'
    ) or
    not(contains(., '::'))
    )

    ]

    关于php - 通过第一个和最后一个字符将字符串与 php dom xpath 匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18613796/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com