[英]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個步驟),因此服務器上的負載也較小。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.