[英]How can I grab the only part of a string that matches a regular expression?
例如,如果我的HTML输入为123Smith456%$@#***()NotSmith
,而我只想要字母字符,那么如何使用正则表达式来匹配并抓住Smith
并将其放入变量中?
You can do this by using the PREG_OFFSET_CAPTURE option in the preg_match function. 您可以通过使用preg_match函数中的PREG_OFFSET_CAPTURE选项来执行此操作。
Your expression needs to be wrapped in () to group the matches you wish to capture. 您的表达式需要包含在()中,以将要捕获的匹配项分组。 You can have any number of groups, so you can capture various parts and store them in various variables.
您可以有任意数量的组,因此可以捕获各个部分并将它们存储在各个变量中。
For example: 例如:
$string = '123Smith456%$@#***()NotSmith';
preg_match('/(Smith)/', $string, $matches, PREG_OFFSET_CAPTURE);
print_r($matches);
This will output: 这将输出:
Array
(
[0] => Array
(
[0] => Smith
[1] => 3
)
[1] => Array
(
[0] => Smith
[1] => 3
)
)
If you are looking to extract all the actual "words" you could do something like this: 如果要提取所有实际的“单词”,则可以执行以下操作:
$string = '123Smith456%$@#***()NotSmith';
preg_match('/([A-Za-z]+)/', $string, $matches, PREG_OFFSET_CAPTURE);
print_r($matches);
This will match all occurrences of anything has characters in the range of AZ or az which occur once or more. 这将匹配所有出现一次或多次出现在AZ或az范围内的字符。 Which outputs:
哪个输出:
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
)
)
)
See: https://secure.php.net/manual/en/function.preg-match.php 参见: https : //secure.php.net/manual/en/function.preg-match.php
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.