![](/img/trans.png)
[英]How can i use a regular expression in PHP that matches a given group in the whole string instead of stops at first match
[英]How can I grab the only part of a string that matches a regular expression?
例如,如果我的HTML輸入為123Smith456%$@#***()NotSmith
,而我只想要字母字符,那么如何使用正則表達式來匹配並抓住Smith
並將其放入變量中?
您可以通過使用preg_match函數中的PREG_OFFSET_CAPTURE選項來執行此操作。
您的表達式需要包含在()中,以將要捕獲的匹配項分組。 您可以有任意數量的組,因此可以捕獲各個部分並將它們存儲在各個變量中。
例如:
$string = '123Smith456%$@#***()NotSmith';
preg_match('/(Smith)/', $string, $matches, PREG_OFFSET_CAPTURE);
print_r($matches);
這將輸出:
Array
(
[0] => Array
(
[0] => Smith
[1] => 3
)
[1] => Array
(
[0] => Smith
[1] => 3
)
)
如果要提取所有實際的“單詞”,則可以執行以下操作:
$string = '123Smith456%$@#***()NotSmith';
preg_match('/([A-Za-z]+)/', $string, $matches, PREG_OFFSET_CAPTURE);
print_r($matches);
這將匹配所有出現一次或多次出現在AZ或az范圍內的字符。 哪個輸出:
Array
(
[0] => Array
(
[0] => Array
(
[0] => Smith
[1] => 3
)
[1] => Array
(
[0] => NotSmith
[1] => 20
)
)
[1] => Array
(
[0] => Array
(
[0] => Smith
[1] => 3
)
[1] => Array
(
[0] => NotSmith
[1] => 20
)
)
)
參見: https : //secure.php.net/manual/en/function.preg-match.php
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.