簡體   English   中英

從正則表達式中獲取變量

[英]get variables from regular expresion

我有以下字符串之一:

mystring
/mystring
mystring?test
/mystring?test

那是一個字符串,前面是一個可選的/ ,然后是和可選的?test

我需要獲取以下變量:

$string = "mystring"
$test = false / true depending if ?test is present

我正在嘗試使用正則表達式,但是在使用正確的模式時遇到了麻煩。 我正在努力:

\/?(\w+)(\??\w+)

例如,對於“ mystring”,我得到了:

Array
(
    [0] => /mystring
    [1] => mystrin
    [2] => g
)

這是一個示例代碼:

<?
echo "<pre>";

$input = "/mystring";

$pattern = "/\/?(\w+)(\??\w+)/";

$matches = null;

preg_match($pattern, $input, $matches);

print_r($matches);
?>

如果您有興趣使用非正則表達式替代方法,可以使用parse_url 它接受部分URL,並且可以解析類似的字符串。

$components = parse_url($input);

$string是除去前斜杠的路徑,而$test是查詢與字符串'test'的相等性。

$string = trim($components['path'], '/');
$test = isset($components['query']) && $components['query'] == 'test';

您包括? 在漁獲量表達中。

您應該使用的正則表達式: \\/?(\\w+)\\??(\\w+)?

這將使用較少的步驟(與regex的56個步驟相比,減少了46個步驟),因此服務器上的負載也較小。

演示: https : //regex101.com/r/98QNeh/2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM