[英]PHP: Get last Tag of a String with Regular Expressions
非常簡單的問題(但困難的解決方案):我在PHP中得到了一個字符串,如下所示:
['one']['two']['three']
然后,我必須提取最后一個標簽,所以我終於得到了three
也可能有一個數字,例如
[1][2][3]
然后我必須拿3
我該如何解決?
謝謝你的幫助!
弗洛
您的標簽為\\[[^\\]]+\\]
。
3個標簽為: (\\[[^\\]]+\\]){3}
最后的3個標簽為: (\\[[^\\]]+\\]){3}$
最后的N個標記為: (\\[[^\\]]+\\])*$
(N 0..n)
例:
<?php
$string = "['one']['two']['three'][1][2][3]['last']";
preg_match("/((?:\[[^\]+]*\]){3})$/", $string, $match);
print_r($match); // Array ( [0] => [2][3]['last'] [1] => [2][3]['last'] )
這是一個可能適合您的正則表達式。 嘗試這個:
[^\[\]']*(?='?\]$)
經過測試的代碼可能適用於您:
function getLastTag($text) {
$re = '/
# Match contents of last [Tag].
\[ # Literal start of last tag.
(?: # Group tag contents alternatives.
\'([^\']+)\' # Either $1: single quoted,
| (\d+) # or $2: un-quoted digits.
) # End group of tag contents alts.
\] # Literal end of last tag.
\s* # Allow trailing whitespace.
$ # Anchor to end of string.
/x';
if (preg_match($re, $text, $matches)) {
if ($matches[1]) return $matches[1]; // Either single quoted,
if ($matches[2]) return $matches[2]; // or non quoted digit.
}
return null; // No match. Return NULL.
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.