如何获取(在 PHP 中)描述正则表达式的所有子字符串?

发布于 2024-10-17 05:55:19 字数 967 浏览 1 评论 0原文

我正在创建以下形式的正则表达式: A |乙| C ... 自动地,通过程序, 其中 A、B、C、... 是常量字符串。

我需要找到与这些正则表达式相对应的所有匹配项, 即使A,B,C,...非空交集,或者某人是其他人的子串

示例:

preg_match_all ('/Hello World|Hello|World lo/i', 'xxxHello worldxxx', $m, PREG_OFFSET_CAPTURE | PREG_SET_ORDER); 
var_export ($m);

它给出:

array (
   0 =>
   array (
     0 =>
     array (
       0 => 'Hello World'
       1 => 3, // start of match
     )
   )
)

我需要:

array (
   0 =>
   array (
     0 =>
     array (
       0 => 'Hello World'
       1 => 3, // start of match
     )
     1 =>
     array (
       0 => 'Hello'
       1 => 3, // start of match
     )
     2 =>
     array (
       0 => 'lo world'
       1 => 6, // start of match
     )
   )
)

有什么办法得到它吗?

谢谢

I'm creating regular expression in the form: A | B | C ... automatically, by program,
where A, B, C, ... are constant strings.

I need to find all the matches that correspond to these regular expression,
even if the A, B, C, ... have not empty intersection, or someone is substring of other.

Example:

preg_match_all ('/Hello World|Hello|World lo/i', 'xxxHello worldxxx', $m, PREG_OFFSET_CAPTURE | PREG_SET_ORDER); 
var_export ($m);

It gives:

array (
   0 =>
   array (
     0 =>
     array (
       0 => 'Hello World'
       1 => 3, // start of match
     )
   )
)

I would need:

array (
   0 =>
   array (
     0 =>
     array (
       0 => 'Hello World'
       1 => 3, // start of match
     )
     1 =>
     array (
       0 => 'Hello'
       1 => 3, // start of match
     )
     2 =>
     array (
       0 => 'lo world'
       1 => 6, // start of match
     )
   )
)

Is there any way to get it?

Thanks

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

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

发布评论

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

评论(2

聚集的泪 2024-10-24 05:55:19

为每个表达式运行 preg_match_all

Run a preg_match_all for each expression.

时常饿 2024-10-24 05:55:19

我会使用 strpos:

$str = 'xxxHello worldxxx';
$arr = array('Hello World', 'Hello', 'World');
foreach($arr as $word) {
    $pos = strpos(strtolower($str), strtolower($word));
    echo "$word found at char $pos\n";
}

输出:

Hello World found at char 3
Hello found at char 3
World found at char 9

I would use strpos:

$str = 'xxxHello worldxxx';
$arr = array('Hello World', 'Hello', 'World');
foreach($arr as $word) {
    $pos = strpos(strtolower($str), strtolower($word));
    echo "$word found at char $pos\n";
}

output:

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