繁体   English   中英

如何使用PHP中的正则表达式在其他两个字符串之间获取字符串?

[英]How I get the string between two other strings using regular expressions in PHP?

我在regexp方面的经验很少。 我想走路

structural/designer/00-slider

在一组中,在第二组中命名

00滑块

使用正则表达式。

以下是声明,

{path:structural/designer/00-slider, name:00-slider}, {path:structural/00-1_1, name:00-1_1}, {path:elements/tab, name:tab}

我用了这个正则表达式

(.+?)path

我得到以下输出,

Match 1
Full match  0-5 `{path`
Group 1.    0-1 `{`
Match 2
Full match  5-58    `:structural/designer/00-slider, name:00-slider}, path`
Group 1.    5-54    `:structural/designer/00-slider, name:00-slider}, `
Match 3
Full match  58-97   `:structural/00-1_1, name:00-1_1}, {path`
Group 1.    58-93   `:structural/00-1_1, name:00-1_1}, {`

如何使用正则表达式实现此目的?

您可以使用

'~{path\s*:\s*(?<path>[^{}]*?), name:(?<name>[^{}]*)}~'

preg_match_all 参见regex演示

细节

  • {path path-文字{path子字符串
  • \\s*:\\s* -用可选的0+空格字符括起来的冒号
  • (?<path>[^{}]*?) -组“ path”:除{}任何0+个字符,尽可能少
  • , name: -文字子字符串
  • (?<name>[^{}]*) -组“名称”: {}以外的任意0+个字符,并尽可能多
  • } -一个} char。

PHP演示

$re = '/{path\s*:\s*(?<path>[^{}]*?), name:(?<name>[^{}]*)}/m';
$str = '{path:structural/designer/00-slider, name:00-slider}, {path:structural/00-1_1, name:00-1_1}, {path:elements/tab, name:tab}';
if (preg_match_all($re, $str, $matches)) {
    print_r($matches['path']); echo "\n";
    print_r($matches['name']);
}

路径

Array
(
    [0] => structural/designer/00-slider
    [1] => structural/00-1_1
    [2] => elements/tab
)

名称

Array
(
    [0] => 00-slider
    [1] => 00-1_1
    [2] => tab
)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM