我有一组字符串如下:
fw-sophi.watcon.-.120
d-elain.heckop.-.121
sim.boosh.-.134
bh.-.elain.heckop.-.244
如何修剪以下字符串集以仅返回中间部分? 预期回报:
sophi.watcon
elain.heckop
sim.boosh
elain.heckop
手动trim()
字符串是不实际的,因为有很多,我将如何以编程方式执行此操作?
答案 0 :(得分:3)
如果没有其他模式,这应该足够了:
$input = 'fw-sophi.watcon.-.120
d-elain.heckop.-.121
sim.boosh.-.134
bh.-.elain.heckop.-.244';
if (preg_match_all('~(?<key>\w+\.\w+)~', $input, $matches)) {
print_r($matches['key']);
}
产生的数组:
Array
(
[0] => sophi.watcon
[1] => elain.heckop
[2] => sim.boosh
[3] => elain.heckop
)
模式说明:
~ #pattern start
( #start group to capture matched result
?<key> #give a name to group. see $matches['key'].
\w+ #one or more alphanumeric characters
\. #dot character. we need to escape it with \
\w+ #one or more alphanumeric characters
) #end group
~ #pattern end
x