簡體   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