0
例如,如果我有一个HTML输入为123Smith456%[email protected]#***()NotSmith
,并且我只想要字母字符,那么我怎样才能使用正则表达式来匹配并抓取Smith
并将其放入一个变量中?如何获取匹配正则表达式的字符串的唯一部分?
例如,如果我有一个HTML输入为123Smith456%[email protected]#***()NotSmith
,并且我只想要字母字符,那么我怎样才能使用正则表达式来匹配并抓取Smith
并将其放入一个变量中?如何获取匹配正则表达式的字符串的唯一部分?
您可以通过使用preg_match函数中的PREG_OFFSET_CAPTURE选项来执行此操作。
你的表情需要用()包裹来分组你想捕获的匹配。您可以有任意数量的组,因此您可以捕获各个部分并将其存储在各种变量中。
例如:
$string = '123Smith456%[email protected]#***()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%[email protected]#***()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
)
)
)
在该问题时,如果你使用'/史密斯/'作为一个正则表达式,它将匹配史密斯,请有关您要输入和输出更清晰 –
@Koala我编辑了这个问题,我如何抓住字母字符给我'Smith'。 –
在像https://regex101.com/r/CbP5Af/1这样的网站上玩正则表达式(我甚至已经开始了你!)阅读PHP手册,'preg_match()'http://php.net/manual /en/function.preg-match.php和'preg_replace()'http://php.net/manual/en/function.preg-replace.php – Steve